博客现已迁移到:http://henderyblog.sinaapp.com 欢迎访问
上一篇写了单链表,双链表在此基础上增加了一些操作。对于求表长度和查找,与单链表基本相同。插入和删除需要修改的指针增多。一些比较特殊位置的操作,如最后一个节点的删除、在最后一个位置插入元素。需要细心。觉得代码还是得多写,写着写着就熟悉了。以下是源码,希望大家多多指点,谢谢!
#include<iostream>
using namespace std;
/**
author:hendery
content:Creat a double linked list and implement the relevent
operations such as:inserting an element,deleteing an
element,search an element,getting the length of the
list,printing the data of all elements and so with it。
time:2012-3-24
*/
struct Node
{
struct Node *prior;
int data;
struct Node *next;
};
Node *CreatDoubleList()//建立双链表
{
Node *head,*node,*temp;
head = (Node*)malloc(sizeof(Node));
head ->next = NULL;
temp = head;
int i = 1;
while(true)
{
node = (Node*)malloc(sizeof(Node));
cout<<"输入第"<<i++<<"节点的值"<<endl;
cin>>node->data;
if(node->data == -1)
break;
temp->next = node;
node->prior = temp;
temp = temp->next;
}
temp->next = NULL;
return head;
}
int length(Node *head)
{
int i = 0;
Node *node;
node = head;
while(node->next!=NULL)
{
node = node->next;
i++;
}
return i;
}
Node *insertElement(Node *head,int i,int data)//i代表插入的位置,data 为插入值
{
if(i>length(head)||i<1)//插入的位置不符要求
{
cout<<"error!";
return NULL;
}
int j = 0;
Node *temp;
temp = head;
//while(temp&&j<i-1)
while(j<i-1&&temp)
{
temp = temp->next;//找到插入节点的位置
j++;
}
Node *node;
node = (Node*)malloc(sizeof(Node));//为要插入的节点申请空间
node->next = temp->next;//要插入的节点的后继指向temp的后继
temp->next->prior = node;//temp的前驱指向node
temp->next = node; //temp的后继指向node
node->prior = temp; //node的前驱指向temp
node->data = data; //写入值
return head; //返回修改后的链表头结点
}
Node *deleteElement(Node *head,int i)
{
if(i>length(head)||i<1)//错误的删除位置
{
cout<<"error!"<<endl;
return NULL;
}
int j = 0;
Node *temp;
temp = head->next;
while(j<i-1&&temp)
{
j++;
temp = temp->next;
}
/*if(temp->next==NULL)
free(temp);
Node *p;
p=temp->next;
temp->next=p->next;
p->next->prior=temp;
free(p);*/
if(temp->next==NULL)
{
temp->prior->next=NULL;//此步骤是关键,在删除最后一个节点时,需要将其的 prior改为尾节点
free(temp);
}
else
{
/*temp为要删除的节点,将temp的prior指向temp的next
temp的next的prior指向temp->prior
*/
temp->prior->next=temp->next;
temp->next->prior=temp->prior;
free(temp);
}
return head;
}
void search(Node *head,int i)//查找链表第i个元素的值,并输出
{
int j = 0;
Node *temp;
temp = head;
while((j++)<i&&temp)
{
temp=temp->next;
}
if(temp==NULL)
{
cout<<"位置有误!"<<endl;
return;
}
cout<<"第"<<i<<"个元素的值为:"<<temp->data<<endl;
}
void print(Node *head)//打印当前链表中的元素
{
Node *node;
node = head->next;
cout<<"当前链表中的元素有:"<<endl;
while(node!=NULL)
{
cout<<node->data<<" ";
node = node->next;
}
}
void main()
{
Node *head;
head = CreatDoubleList();
int len;
len = length(head);
cout<<"length of list is:"<<len<<endl;
print(head);
int location,data;
cout<<"输入要插入节点的位置和值"<<endl;
cout<<"位置:";
cin>>location;
cout<<"值:";
cin>>data;
insertElement(head,location,data);
print(head);
int i;
cout<<"输入要删除节点的位置"<<endl;
cin>>i;
deleteElement(head,i);
cout<<"此时链表的长度为:"<<length(head)<<endl;
print(head);
int s;
cout<<"输入要查找节点的位置";
cin>>s;
search(head,s);
system("pause");
}