C雙向鏈表
寫了一個很簡單的雙向鏈表
#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;
}
界麵變成了:

最後更新:2017-04-03 05:39:11