列表元素的插入与删除

// 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值