雙鏈表的插入 刪除

來源:互聯網
上載者:User

雙鏈表其實 也沒什麼 只是多了一個前置鏈而已

雙鏈表的定義

struct DNode{int data;struct DNode *next;struct DNode *pre;};

 

單鏈表的定義

struct DNode{int data;struct DNode *next;};

其他的可以看上一篇部落格  大致相同

#ifndef HEAD_H#define HEAD_H#include <iostream>using namespace std;#include <cassert>#include <cstdlib>#include <cmath>#include <sstream>#include <fstream>#include <string>#include <algorithm>#include <list>#include <queue>#include <vector>#include <deque>#include <stack>#include <bitset>#include <set>#include <map>#endifstruct DNode{int data;struct DNode *next;struct DNode *pre;};DNode *Creat(){DNode *head,*p,*s;head=(DNode *)malloc(sizeof(DNode));p=head;int temp;while (cin>>temp&&temp){s=(DNode *)malloc(sizeof(DNode));s->data=temp;p->next=s;s->pre=p;p=s;}head=head->next;p->next=NULL;head->pre=NULL;return (head);}DNode *Insert(DNode *&head,int num){DNode *p,*s;s=(DNode *)malloc(sizeof(DNode));s->data=num;p=head;while (NULL!=p->next&&num>p->data){p=p->next;}if (num<=p->data){if (NULL==p->pre){s->next=head;head->pre=s;head=s;head->pre=NULL;} else{s->pre=p->pre;p->pre->next=s;s->next=p;p->pre=s;}} else{p->next=s;s->pre=p;s->next=NULL;}return(head);}DNode *Del(DNode *&head,int num){DNode *p;p=head;while (NULL!=p->next&&num!=p->data){p=p->next;}if (num==p->data){if (NULL==p->pre){head=p->next;p->next->pre=head;free(p);} else if (NULL==p->next){p->pre->next=NULL;free(p);}else{p->pre->next=p->next;p->next->pre=p->pre;free(p);}} else{cout<<num<<" cound not be found"<<endl;}return head;}void Display(DNode *head){DNode *p;p=head;while (NULL!=p){cout<<(p->data)<<" ";p=p->next;}cout<<endl;}

 

#include "head.h"int main(){DNode *head;head=Creat();Display(head);#ifndef DEBUGcout<<"please input an num to insert:";#endifint insert_num;while (cin>>insert_num&&insert_num){Insert(head,insert_num);Display(head);}#ifndef DEBUGcout<<"please input an number to delete:";#endif    int delete_num;    while (cin>>delete_num&&delete_num)    {Del(head,delete_num);Display(head);    }return (EXIT_SUCCESS);}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.