C++双向链表创建及添加元素
双向链表
双向链表和单链表相比,多了一个前驱指针指向前一个结点
下面代码分别对非循环的和循环的双向链表进行创建
#include <iostream>
#include <string>
using namespace std;
#define OK 1
#define FALSE 0
typedef int Status;
typedef int ElemType;
typedef struct Node
{
ElemType data;
struct Node *next; //后继指针
struct Node *prior; //前驱指针
};
typedef Node *Link; //链
Status CreatOneWayList(Link *L, int n) //构建非循环的
{
*L = (Link)malloc(sizeof(Node)); //头结点
Link p = *L;
(*L)->prior = NULL; //头结点的前驱为空
for (int i = 1; i <= n; i++)
{
Link s = (Link)malloc(sizeof(Node)); //新结点s
s->data = i;
p->next = s; //前一个结点p的后继指针指向s
s->prior = p; //s的前驱指针指向p
p = s; //更新p
}
p->next = NULL;
return OK;
}
//循环双向链表构建方式和非循环的一样,只需更改头结点前驱指针指向和尾结点后继指针指向
Status CreatTwoWayList(Link *L, int n)
{
*L = (Link)malloc(sizeof(Node));
(*L)->data = 10000;
Link p = *L;
for (int i = 1; i <= n; i++)
{
Link s = (Link)malloc(sizeof(Node));
s->data = i;
p->next = s;
s->prior = p;
p = s;
}
p->next = (*L);
(*L)->prior = p;
return OK;
}
Status TraverseList(Link L, int n)
{
Link p = L->next;
Link s = L;
for (int i = 0; i < n; i++)
{
cout << p->data << " ";
p = p->next;
s = s->next;
}
cout << endl;
for (int i = 0; i < n; i++)
{
cout << s->data << " ";
s = s->prior;
}
cout << endl;
return OK;
}
Status ListInsert(Link *L, ElemType m, int n)
{
Link p = *L; //用来找到插入位置的前一个结点
for (int i = 0; i < n-1; i++)
{
p = p->next;
}
Link s = (Link)malloc(sizeof(Node));//新的结点
s->data = m; //新结点的值
s->prior = p; //新结点的前驱
s->next = p->next; //新结点的后继
p->next = s; //插入位置前一个结点后继
s->next->prior = s; //插入位置后一个位置的前驱
return OK;
}
int main()
{
Link A;
int n = 10;
CreatOneWayList(&A, n);
cout << "链表A:" << endl;
TraverseList(A, n);
ListInsert(&A, 100, 2);
cout << "在链表A的第二个位置插入100后,链表A;" << endl;
TraverseList(A, n+1);
Link B;
int b = 15;
CreatTwoWayList(&B, b);
cout << "链表B:" << endl;
TraverseList(B, 2*b);
ListInsert(&B, 100, 2);
cout << "在链表B的第二个位置插入100后,链表B:" << endl;
TraverseList(B, 2 * (b + 1));
system("pause");
return 0;
}
程序运行结果(在循环双向链表的头结点内添加data=10000,便于输出):