雙鏈表的簡單應用

來源:互聯網
上載者:User

標籤:儲存   iostream   c++   指標   雙鏈表   

/*當對單鏈表理解後,對雙鏈表就好理解多了,單鏈表就是只有在結構體或者類中只有一個指標用來儲存下一個節點的地址,雙鏈表就是在裡面有兩個指標,一個用來儲存上一個節點的地址,一個用來儲存下一個節點的地址。這樣的鏈表就叫雙鏈表。*/

#include<iostream>

using namespace std;
struct Node
{
    int a;
    Node *prior,*next;         //前指標,後指標
};
int main()
{
    Node *first,*r,*p;
    first=new Node();    //因為在一個雙鏈表中插入資料要用到它的前一個節點,或者後一個節點,所以這兒r就代表first的後一個節點,下面會用到
    r=new Node();
    first->next=r;
    r->prior=NULL;
    for(int i=20;i>=0;i--)      //將21個p指標依次插入以first為頭結點的鏈表中。
    {
        p=new Node();
        p->a=i;                                
        p->next=first->next;       //p的next指標儲存了first 的next指標儲存的地址,
        p->prior=first;                //p的前一個節點就是first,所以prior中存的是first的地址
        first->next->prior=p;    //first原來的節點現在儲存的是p的地址。
        first->next=p;                //first的下一個節點就是p,  這兒四條語句的先後順序需要注意一下
    }
    p=first->next;
    for(int i=0;i<=20;i+=2)
    {
        while(p->next!=NULL)
        {
            if(p->a==i)
            {
                p->prior->next=p->next;      //這兒是刪除a值為偶數的節點,剩下的為奇數節點
                p->next->prior=p->prior;
                cout<<p->a<<" ";
                delete p;
                break;
            }
            p=p->next;
        }
    }
    p=first->next;
    cout<<endl;
    while(p->next!=NULL)
    { 
        cout<<p->a<<" ";                             //輸出的是奇數節點
        p=p->next;
    }
}

雙鏈表的簡單應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.