写了一个很简单的双向链表
#include <stdio.h> #include <STDLIB.H> #include <MALLOC.H> //一个简单链表,只有一条链 typedef struct FUCK{ int data; struct FUCK * pre; struct FUCK * next; }Node; Node *head=NULL; void initList() { head=(Node*)malloc(sizeof(Node)); head->next=NULL; head->pre=NULL; } Node* find(int a) { //找到插入点,在插入点的后面插入a元素 Node *point=NULL; point=head->next; while(1) { if (a<=point->data) { return point->pre; } if (point->next==NULL) break; point=point->next; } return point; } void insertE(int a) { Node *p=NULL; p=(Node *)malloc(sizeof(Node)); //写入新节点内容 p->data=a; p->next=NULL; p->pre=NULL; if(head->next==NULL) { //证明链表现在是空的 head->next=p; p->pre=head; } else { //链表不空,找到插入点 Node* insPoint=find(a); Node* insPNext=insPoint->next; //记录原插入点的后一个节点 //处理前一个点 insPoint->next=p; p->pre=insPoint; //处理后一个点,情况稍微复杂一点,要考虑null的情况 if(insPNext!=NULL) { insPNext->pre=p; p->next=insPNext; } else { p->next=NULL; //这句可以不写,因为前面有初始化,但是为了清楚还是写上 } } //至此已成功插入 } void traversal() { Node *point; point=head->next; while(point!=NULL) { printf("%d ",point->data); point=point->next; } printf("\n"); } int main() { initList(); insertE(1); insertE(2); insertE(15); insertE(9); //遍历链表 traversal(); return 0; }
输出结果:1 2 9 15
#include <stdio.h> #include <STDLIB.H> #include <MALLOC.H> //一个简单链表,只有一条链 typedef struct FUCK{ int data; struct FUCK * pre; struct FUCK * next; }Node; Node *head=NULL; void initList() { head=(Node*)malloc(sizeof(Node)); head->next=NULL; head->pre=NULL; } Node* find(int a) { //找到插入点,在插入点的后面插入a元素 Node *point=NULL; point=head->next; while(1) { if (a<=point->data) { return point->pre; } if (point->next==NULL) break; point=point->next; } return point; } void insertE(int a) { Node *p=NULL; p=(Node *)malloc(sizeof(Node)); //写入新节点内容 p->data=a; p->next=NULL; p->pre=NULL; if(head->next==NULL) { //证明链表现在是空的 head->next=p; p->pre=head; } else { //链表不空,找到插入点 Node* insPoint=find(a); Node* insPNext=insPoint->next; //记录原插入点的后一个节点 //处理前一个点 insPoint->next=p; p->pre=insPoint; //处理后一个点,情况稍微复杂一点,要考虑null的情况 if(insPNext!=NULL) { insPNext->pre=p; p->next=insPNext; } else { p->next=NULL; //这句可以不写,因为前面有初始化,但是为了清楚还是写上 } } //至此已成功插入 } void traversal() { Node *point; point=head->next; while(point!=NULL) { printf("%d ",point->data); point=point->next; } printf("\n"); } int main() { initList(); int a; while(1) { printf("please enter an insert number:\n"); scanf("%d",&a); insertE(a); printf("now the numbers in the list are:\n"); //遍历链表 traversal(); getchar(); getchar(); system("CLS"); } return 0; }
界面变成了: