双链表的创建,求长,插入,删除,打印,释放(循环和非循环)
生活随笔
收集整理的這篇文章主要介紹了
双链表的创建,求长,插入,删除,打印,释放(循环和非循环)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
鏈接地址:http://blog.csdn.net/stpeace/article/details/8112462
#include<iostream>using namespace std;typedef struct Node
{int data;struct Node *prior; struct Node *next;
}Node,*DList;//DList用來(lái)指向一個(gè)鏈表,Node *定義的函數(shù)用來(lái)返回其中一個(gè)節(jié)點(diǎn)的地址DList createDList1()//輸入數(shù)據(jù)創(chuàng)建循環(huán)鏈表
{int num;Node *head,*p1,*p2;//p1指向新創(chuàng)建的節(jié)點(diǎn),p2指向新創(chuàng)建之前的一個(gè)節(jié)點(diǎn)head=new head;p1=p2=head->prior=head->next=head;cin>>num;while(0!=num){p1=new Node;p1->data=num;p2->next=p1;//不能是head->nextp1->next=head;p1->prior=p2;head->prior=p1;p2=p1;//不可少cin>>num;}return head;
}void createDList(Node *&L,int a[],int n)//創(chuàng)建雙鏈表(利用數(shù)組)
{Node *s,*r;int i;L=new Node;L->next=NULL;r=L;for(i=0;i<n;i++){s=new Node;s->data=a[i];r->next=s;//在此之前,r代表第一個(gè)節(jié)點(diǎn)(頭結(jié)點(diǎn)),s為第二個(gè)節(jié)點(diǎn)s->prior=r;//prior指向它前一個(gè)r=s;}r->next=NULL;
}DList searchNode(Node *C,int x)//查找指定的數(shù)據(jù),返回節(jié)點(diǎn)
{Node *p=C->next;//C為頭結(jié)點(diǎn),里面沒(méi)有數(shù)據(jù)while(p!=NULL){if(p->data==x){break;//結(jié)束整個(gè)循環(huán),continue結(jié)束單個(gè)循環(huán),if中的條件成立后,將不執(zhí)行p=p->next,是continue則會(huì)執(zhí)行}p=p->next;}return p;
}int getDListLength(DList p)//循環(huán)雙鏈表求長(zhǎng)(和雙鏈表求長(zhǎng)不一樣),不帶頭結(jié)點(diǎn)
{int length=0;Node *head=p//普通雙鏈表不需要這樣定義while(head!=p->next)//普通雙鏈表的判斷條件是NULL!=p->next{length++;p=p->next;}return length;
}Node *getlocation(DList p,int location)//循環(huán)雙鏈表的定位,找到某一個(gè)位置返回其指針
{//為了程序的健壯,這里還要對(duì)location進(jìn)行判斷Node *head=p;int i;for(i=0;head!=p->next&&i<location;i++){p=p->next;}return p;
}void insertNode(DList p,int location,int element)//循環(huán)鏈表的插入,插在指定位置的后面
{Node *q=getlocation(p,location);Node *s=new Node;//新建一個(gè)節(jié)點(diǎn)插入s->data=element;s->prior=q;s->next=q->next;q->next->prior=s;//q->next表示之前q之前的后一個(gè)節(jié)點(diǎn),這段代碼表示q之前的后一個(gè)節(jié)點(diǎn)的prior指向q->next=s;
}void delNode(DList p,int location)
{Node *q=getlocation(p,location);//刪除這個(gè)qq->prior->next=q->next;//q->next表示q之前的那個(gè)節(jié)點(diǎn)q->next->prior=q->prior;//q->next表示q之后的那個(gè)節(jié)點(diǎn)delete p;
}void release(DList p)//釋放循環(huán)雙鏈表
{Node *head=p;if(head==p->next)delete p; else{release(p->next);delete p;}
}void print(DList p)//打印環(huán)狀
{Node *head=p;//指針初始化,此時(shí)head表示頭結(jié)點(diǎn)的地址while(head!=p->next)//循環(huán)的,最后又指向頭結(jié)點(diǎn){cout<<p->next->data<<endl;p=p->next;}
}void print1(DList p)//打印非循環(huán)雙鏈表
{while(NULL!=p->next){cout<<p->next->data<<endl;p=p->next;}
}int main()
{DList head,head1;int a[5]={1,2,3,4,5};createDList(head,a,5);print1(head);DList head2=createDList();print(head2);int location=2;int element=5;insertNode(head2,location,element);print(head2);int location1=2;delNode(head2,location);print(head2);release(head2);}
?
總結(jié)
以上是生活随笔為你收集整理的双链表的创建,求长,插入,删除,打印,释放(循环和非循环)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 单链表建立(头插法,头插法,用数组),求
- 下一篇: 单链表的的逆置(带头结点)