双链表的建立以及插入,删除操作

本文介绍了一个使用C++实现的双链表基本操作案例,包括创建、插入、删除及遍历等功能。通过具体代码展示了如何进行节点的增删改查,并提供了一个简单的主程序来演示这些操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >




//双链表
#include<iostream>
#include<string>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

typedef struct student
{
	int data;
	struct student *next;
	struct student *prior;
}node;

node *creatlist()
{
	node *head, *p, *q;
	int x;
	head = (node*)malloc(sizeof(node));
	head->next = NULL;
	head->prior = NULL;
	//p = head->next;   头插入法要用的;
	p = head;
	cout << "请输入数据,以ctrl+z表示结束" << endl;
	//这是头插入法;
	/*while (cin >> x)
	{
		q = (node*)malloc(sizeof(node));
		q->data = x;
		q->prior = head;
		q->next = p;
		head->next = q;
		
		p = q;
	}*/
	//这是尾插入法;输出顺序和头插入不一样;
	while (cin >> x)
	{
		q = (node*)malloc(sizeof(node));
		q->data = x;
		q->next = p->next;
		q->prior = p;
		p->next = q;
		p = q;
	}
	return(head);
}

void printlist(node *head)
{
	node *p;
	p = head->next;
	cout << "当前双链表数据为:" << endl;
	while (p != NULL)
	{
		cout << p->data << endl;
		p = p->next;
	}
	
}

//插入;
void insert(node *r, int x)
{
	node *p;
	p = (node*)malloc(sizeof(node));
	p->data = x;
	p->next = r->next;
	p->prior = r;
	r->next->prior = p;
	r->next = p;
}

//删除;
void deletelist(node *head, int x)
{
	node *p, *q;
	q = head;
	p = head->next;
	while (p != NULL && p->data != x)
	{
		q = p;
		p = p->next;
	}
	if (p == NULL)
		cout << "该链表没有这个数值" << endl;
	else {
		q->next = p->next;
		p->next->prior = q;
		free(p);
	}

}


int main()
{
	node *head;
	head = creatlist();
	insert(head, 88);
	deletelist(head, 5);
	printlist(head);
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值