structlist { int value;//数据 list *next;//后指针 list *pre;//前指针 };//链表结构体
4.初始化
我们已经创建好了一个链表,那么需要对它进行初始化操作,书写初始化函数。
我们需要为head和tail开一个新的空间,否则将成为一个没空间没内存的“野指针”。
1 2 3 4 5 6 7 8 9 10
voidinitialization(list *&head, list *&tail)//传入头指针与尾指针 { head = newlist (); tail = newlist (); //为head、tail开空间 head -> next = tail;//head的"next"指向tail head -> pre = NULL;//head的"pre"指向NULL(空) tail -> pre = head;//tail的"next"指向tail tail -> next = NULL;//tail的"next"指向NULL(空) }//初始化
voidinsert(list *&tail, int v) { list *p = newlist (); list *q = newlist (); q = tail -> pre; p -> value = v; p -> next = tail; tail -> pre = p; p -> pre = q; q -> next = p; }//添加
voidDelete(list *&head, int v) { list *p = head; p = p -> next; while(p -> next != NULL) { if(p -> value == v) { p -> next -> pre = p -> pre; p -> pre -> next = p -> next; break; } p = p -> next; } }//删除
voidEmpty(list *head) { list *p = newlist (); list *HEAD = head; HEAD = HEAD -> next; while(HEAD -> next != NULL) { p = HEAD -> next; HEAD -> next -> pre = HEAD -> pre; HEAD -> pre -> next = HEAD -> next; delete HEAD; HEAD = p; } }//清空
8.完整代码
网上很多代码都写了“typedef”,身边一些同学也这么写过,据了解后发现“typedef”在c语言书写时会较轻松。 因为c语言在定义一个指针时不能直接“list xxx”,而需要“struct list xxx”。
#include<iostream> usingnamespacestd; structlist { int value;//数值 list *next;//下一个 list *pre;//上一个 };//链表结构体 int x; voidinitialization(list *&head, list *&tail) { head = newlist (); tail = newlist (); head -> next = tail; head -> pre = NULL; tail -> pre = head; tail -> next = NULL; }//初始化 voidinsert(list *&tail, int v) { list *p = newlist (); list *q = newlist (); q = tail -> pre; p -> value = v; p -> next = tail; tail -> pre = p; p -> pre = q; q -> next = p; }//添加 voidEmpty(list *&head) { list *p = newlist (); list *HEAD = head; HEAD = HEAD -> next; while(HEAD -> next != NULL) { p = HEAD -> next; HEAD -> next -> pre = HEAD -> pre; HEAD -> pre -> next = HEAD -> next; delete HEAD; HEAD = p; } }//清空 voidDelete(list *&head, int v) { list *p = head; p = p -> next; while(p -> next != NULL) { if(p -> value == v) { p -> next -> pre = p -> pre; p -> pre -> next = p -> next; break; } p = p -> next; } }//删除 voidprint(list *head) { cout << "开始打印" << endl; head = head -> next; while(head -> next != NULL) { cout << head -> value << endl; head = head -> next; } cout << "结束打印" << endl; }//打印 intmain() { list *head, *tail; initialization(head, tail); while(1) { cout << "1.insert" << endl << "2.Empty" << endl << "3.print" << endl << "4.Delete" << endl << "5.EXIT" << endl; cin >> x; switch(x) { case1: cin >> x; insert(tail, x); break; case2: Empty(head); break; case3: print(head); break; case4: cin >> x; Delete(head, x); break; case5: return0; } } return0; }