#include <stdio.h>
#include <stdlib.h>
typedef struct n {
int data;
struct n* pre;
struct n* next;
}*node;
node create_node();
void print(node head);
node insert(node head, int i);
node deleteNode(node head, int i);
int main()
{
node head = create_node();
print(head);
head = insert(head, 11);
print(head);
head = deleteNode(head, 9);
print(head);
}
node create_node()
{
node head, p, s;
int x;
head = (node)malloc(sizeof(struct n));
p = head;
while(scanf("%d", &x)&&x) {
s = (node)malloc(sizeof(struct n));
s->data = x;
s->pre = p;
p->next = s;
p = s;
}
p->next = NULL;
head = head->next;
head->pre = NULL;
return head;
}
void print(node head) {
node p;
p = head;
printf("正序输出链表:\n");
while(p) {
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
node insert(node head, int i) {
node temp = (node)malloc(sizeof(struct n));
temp->data = i;
node p = head;
if(i < p->data) {
temp->next = p;
temp->pre = NULL;
p->pre = temp;
return temp;
}
while(p->next && i>p->data) {
p = p->next;
}
if(i <= p->data) {
temp->next = p;
temp->pre = p->pre;
p->pre->next = temp;
p->pre = temp;
} else {
p->next = temp;
temp->pre = p;
temp->next = NULL;
}
return head;
}
node deleteNode(node head, int i) {
node p = head;
if(i == p->data) {
head = head->next;
p->next = NULL;
head->pre = NULL;
free(p);
return head;
}
while(p && i!=p->data) {
p = p->next;
}
if(p && i==p->data) {
p->pre->next = p->next;
p->next->pre = p->pre;
free(p);
} else {
printf("delete error\n");
}
return head;
}
|