双链表的建立、查找、删除、插入
来源:互联网 发布:js input text 选中 编辑:程序博客网 时间:2024/06/01 09:13
#include <iostream>#include <stdio.h>#include <string.h>#include <conio.h>using namespace std;typedef struct student{ int data; struct student *next; struct student *pre;}dnode;//双链表的建立dnode * creat(){ dnode *head,*p,*s; int x,cycle =1; head = (dnode*)malloc(sizeof(dnode)); p=head; while(cycle) { printf("\n 请输入数据:"); scanf("%d",&x); if (x !=0) { s= (dnode*) malloc(sizeof(dnode)); s->data = x; printf("\n %d",s->data); p->next = s; s->pre =p; p= s; } else cycle = 0;} head = head->next;//此时的head指向双链表中第一个有数据元素的节点 head->pre= NULL; p->next =NULL; printf("\n 第一个有数据元素的节点的数据:%d",head->data); return (head);}//双链表的查找dnode *find(dnode *head, int num){ dnode *p; p1 = head; while(p != NULL && p1->data !=num) { p=p->next; } if (p=NULL) { printf("未找到该数据"); } return p;}//双链表的删除dnode *del(dnode *head, int num){ dnode *p1,*p2; p1 = head; while(num != p1->data && p1->next !=NULL) { p1=p1->next; } if (num == p1->data) { if(p1==head)//要删除的节点为表头节点 { head=head->next; head->pre =NULL; } else if(p1->next == NULL)//要删除的节点为表尾节点 { p1->pre->next = NULL; } else//要删除的节点处于表中间 { p1->next->pre = p1->pre; p1->pre->next = p1->next; } free(p1); } else printf("\n %d 未找到该数据",num); return (head);}//双链表的插入dnode *insert(dnode *head,int num){ dnode *p0,*p1; p1=head; p0=(dnode*)malloc(sizeof(dnode)); p0->data = num; while(p0->data >p1->data && p1->next != NULL) { p1=p1->next; } //三种位置的插入,表头,表尾,表中间 if (p0->data <= p1->data) { if (head == p1) //在表头插入节点 { p0->next =p1; p1->pre = p0; head =p0; } else //在表中间插入节点 { p1->pre->next=p0; p0->next =p1; p0->pre=p1->pre; p1->pre =p0; } } else //在表尾插入节点 { p1->next =p0; p0->pre=p1; p0->next=NULL; }}int main() { dnode *head,stud; int n,del_num,insert_num; head = creat(); print(head); cout < "\n nInt: "; cin >> del_num; head = del(head,del_num); print(head); cout << "\n 请输入要插入的数据:"; cin >> insert_num; head = insert(head,insert_num); print(head); return 0;}