// test5.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <malloc.h>
#include <iostream>
using namespace std;
struct DuLNode
{
int data;
DuLNode *prior;
DuLNode *next;
};
typedef DuLNode *DuLinkList;
bool DuListInsert(DuLinkList L,int i,int e) //插入函数
{
DuLinkList p = L; //判断p是否到最后一个数据
DuLinkList q = L;
int j = 0;
while(p->next != L && j < i) //判断p是否到最后一个数据
{
p = p->next;
j++;
}
if(p->next == L || j<i) //如果p是最后一个节点或者插入位置大于链表节点数
{
printf("无效的插入位置!\n");
return 0;
}
//创建新节点q,数据为e,指针为null
q = (DuLinkList)malloc(sizeof(DuLNode));
q->data = e;
q->prior = p->prior;
q->next = p;
p->prior->next = q;
p->prior = q;
return 1;
}
bool DuListDelete(DuLinkList L,int i,int &e)
{
DuLinkList p =L;
int j = 0;
while(p->next != L && j < i)
{
p = p->next;
j++;
}
if(p->next == L && j < i)
{
return 0;
}
p->prior->next = p->next;
p->next->prior = p->prior;
e = p->data;
free(p);
return 1;
}
int main(int argc, char* argv[])
{
//初始化双向循环列表
DuLinkList L;
L = (DuLinkList)malloc(sizeof(DuLNode)); //创建空双列表
L->next = L->prior = L;
DuLNode *p,*q;
int e;
p = L;
q = L;
while(cin >> e)
{
p->next = (DuLinkList)malloc(sizeof(DuLNode));
q = p;
p = p->next; //p指向新的节点
p->data = e; //新节点的数据为刚输入的e
p->next = L; //新结点的指针域为头结点,表示这是单链表的最后一个结点
p->prior = q;
L->prior = p;
}
p = L;
while(p->next != L)
{
cout << p->next->data << ' ';
p = p->next;
}
cin.clear();
cin.ignore();
int i;
cout << "\n输入待插入的元素e:";
cin >> e;
cout << "\n输入待插入的位置i:";
cin >> i;
if(DuListInsert(L,i,e))
{
cout << "插入后的双链为:";
p = L;
while(p->next != L)
{
cout << p->next->data << ' ';
p = p->next;
}
}
printf("\n");
p = L;
while(p->next != L)
{
cout << p->next->data << ' ';
p = p->next;
}
int k;
cin.clear();
cin.ignore();
cout<<"要删除第几个节点k:";
cin >> k;
if(DuListDelete(L,k,e))
{
cout << "被删除的元素为:" << e << endl;
cout << "删除后的元素为:";
p = L;
while(p->next != L)
{
cout << p->next->data << ' ';
p = p->next;
}
}
else cout << "删除出错";
return 0;
}