您的位置:首页 > 其它

双链表的创建、插入、删除

2007-04-25 12:10 176 查看

#include<stdio.h>


#include<malloc.h>




typedef struct node //定义双链表




...{


int data;


struct node *prior;


struct node *next;


}snode;




snode *creat() //创建双链表




...{


snode *head, *p, *q;


int x;


head = (snode *)malloc(sizeof(snode));


q = head;


printf("请输入创建双链表的值,以-1结束. ");


printf("x = ");


scanf("%d", &x);


while (x != -1)




...{


p = (snode *)malloc(sizeof(snode));


p->data = x;


q->next = p;


p->prior = q;


q = p;


printf("x = ");


scanf("%d", &x);


}


q->next = NULL;


return head;


}




void display(snode *head)




...{


snode *p = head->next;


while (p != NULL)




...{


printf("%4d", p->data);


p = p->next;


}


printf(" ");


}




int length(snode *head)//测链表的结点数




...{


snode *p = head->next;


int i = 0;


while (p != NULL)




...{


p = p->next;


i++;


}


return i;


}




void opposite(snode *head)




...{


snode *p = head->next;


while (p->next != NULL)


p = p->next;


while (p != head)




...{


printf("%4d", p->data);


p = p->prior;


}


printf(" ");


}




int insnode(snode *head, int x, int i) //把x插入到链表的第i的位置




...{


snode *p = head->next, *s;


if(i < 1 || i > length(head) + 1)


return 0;


else if (i == 1)




...{


s = (snode *)malloc(sizeof(snode)); //分配内存


s->next = p;


p->prior = s;


s->prior = head;


head->next = s;


s->data = x;


}


else




...{


s = (snode *)malloc(sizeof(snode)); //分配内存


for (int j = 1; j < i - 1; j++)


p = p->next;


if (p->next != NULL)




...{


s->next = p->next;


p->next->prior = s;


p->next = s;


s->prior = p;


s->data = x;


}


else




...{


s->next = NULL;


p->next = s;


s->prior = p;


s->data = x;


}


}


return 1;


}




int delnode(snode *head, int i)//删除链表中第i个结点




...{


snode *p = head->next, *q = head;


if(i < 1 || i > length(head))


return 0;


else




...{


for (int j = 1; j < i; j++)




...{


p = p->next;


q = q->next;


}


if (p->next != NULL)




...{


q->next = p->next;


p->next->prior = q;


}


else


q->next = p->next;


free(p);


}


return 1;


}


int main(void)




...{


snode *headl = creat(); //创建双链表


printf("最初的链表如下: ");


display(headl);


printf("为了证明是双链表反向输出: ");


opposite(headl);


int num, location;


printf("请分别输入您要插入到链表中的数以及想插入的位置:");


scanf("%d %d", &num, &location);


if (insnode(headl, num, location))




...{


printf("插入新值以后的链表如下: ");


display(headl);


printf("为了证明插入新值以后仍然是双链表,反向输出如下: ");


opposite(headl);


}


else


printf("输入有误 ");


printf("请输入您想删除的结点位置:");


scanf("%d", &location);


if (delnode(headl, location))




...{


printf("删除第%d个结点后的链表如下: ", location);


display(headl);


printf("为了证明删除一个结点以后仍然是双链表,反向输出如下: ");


opposite(headl);


}


else


printf("输入有误! ");


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: