数据结构之双向链表,头部插入数据
来源:互联网 发布:淘宝买家黑名单网站 编辑:程序博客网 时间:2024/06/13 19:35
#include <stdio.h>#include <stdlib.h>/*双向链表,在表头插入数据*/typedef struct node{int key;struct node *Next;struct node *Pre;}Node;void Insert(int num,Node *head)//插入新的节点 {Node *p = NULL;p = (Node *) malloc (sizeof(Node));//开辟新的节点 p->key = num;//赋值 if(head->Next==NULL)//如果是空链表 { p->Next=NULL;p->Pre=NULL;head->Next=p;//将原来的头结点挂在新节点后,并把新节点挂在表头上 } else //非空链表,则把旧元素的pre指向p,并将p的next指向原来的头元素 { head->Next->Pre=p; p->Next=head->Next; head->Next=p; }}void Print_List(Node *head){Node *p = head->Next;while(p != NULL)//遍历打印节点值 {printf("%d->", p->key);p = p->Next;}printf("\n");}Node *Search_List(Node *head,int num)//寻找值为num的节点,并返回位置指针 { Node *p=NULL; p=head; while((p->Next!=NULL)&&p->key!=num) p=p->Next; if(p->Next==NULL&&p->key!=num) { printf("不存在值为%d的节点,将返回头结点",num); return head; } return p; } void Delete_List(Node *head,int num)//删除值为num的节点{ Node *p=NULL; p=Search_List(head,num);//找打要删除的节点 if(p==head) printf("没有要删除的元素"); else if(p->Pre==NULL)//说明是第一个节点 { head->Next=p->Next; p->Next->Pre=NULL; } else if(p->Next==NULL)//说明是尾节点 { p->Pre->Next=NULL; } else //普通的节点 { p->Pre->Next=p->Next; p->Next->Pre=p->Pre; } } int main(){int i;Node *p=NULL;Node *head = (Node *)malloc(sizeof(Node));head->Next = NULL;//建立空表头 for (i=0; i<10; i++){Insert(i, head);}Print_List(head);printf("输入你要查找的值:");scanf("%d",&i);p=Search_List(head,i);printf("已查到节点,值为:%d",p->key); printf("输入你要删除的值:");scanf("%d",&i);Delete_List(head,i);printf("删除以后\n");Print_List(head);system("PAUSE");return 0;}