论坛首页 编程语言技术论坛

循环双链表的增删

浏览 2083 次
精华帖 (1) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-06-29  
C
#include<stdio.h>
#include<stdlib.h>
//#include<string.h>
#include<iostream>

using namespace std;

typedef struct Node{
  char ch;
  Node * prior;
  Node * next;
}Node,* Linklist;

//构建循环双链表
Node * createRoteLinklist()
{
  Linklist L=(Node *)malloc(sizeof(Node));
  Node *r;char _char;
  L->ch='$';r=L;
  cin>>_char;
  while(_char!='$')
  {
     Node *s=(Node *)malloc(sizeof(Node));
     s->ch=_char;
     r->next=s;
     s->prior=r;
     r=r->next;
     cin>>_char;
  }
  //free(s);
  r->next=L;
  L->prior=r;
  return L;
}

Node* insertNode(char ch,Node * rear,Linklist L)
{
  Node *s=(Node *)malloc(sizeof(Node));
  s->ch=ch;
  rear->next=s;
  s->prior=rear;
  s->next=L;
  L->prior=s;
  return rear=rear->next;
}

//头尾同时查找要删除的元素
int deleteNode(char ch,Node *rear,Linklist L)
{
  Node *p=L->next;
  Node *q=rear;
  while(p!=q)
  {
     if(p->ch==ch||q->ch==ch){
        if(p->ch==ch){
           p->prior->next=p->next;
           p->next->prior=p->prior;
           free(p);
           return 0 ;
        }
        else if(q->ch==ch){
           q->prior->next=q->next;
           q->next->prior=q->prior;
           free(q);
           return 0 ;
        }
    }
    p=p->next;q=q->prior;
  }
  cout<<"delete Node can not found\n";
  return 0;
}

//输出当前链表的情况
void procOutput(Linklist L,Node * rear)
{
  Node * p=L->next;
  int i=0;
  cout<<"当前结点情况为:\n";
  while(p!=L)
  {
     cout<<"ID"<<++i<<":"<<p->ch<<" ";
     p=p->next;
  }
  cout<<"\n";
}

int main()
{
  char ch;
  Linklist L=createRoteLinklist();
  Node * rear=L->prior;
  procOutput(L,rear);
  cin>>ch;
  rear= insertNode(ch,rear,L);//尾部插入一个结点
  procOutput(L,rear);
  cin>>ch;
  deleteNode(ch,rear,L);//删除结点
  procOutput(L,rear);
  return 0;
}
 
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics