双链表的创建、测长、打印、插入和删除

内容RT,实现代码如下所示:

#include <iostream>
#include <stdio.h>
#include <string>

using namespace std;

typedef struct student
{
	int data;
	struct student *next;
	struct student *pre;
}dnode;

// 建立双链表
dnode *creat()
{
	dnode *head, *p, *s;
	int x, cycle = 1;
	head = new dnode;
	p = head;

	while (cycle)
	{
		cout << "Please input data for dnode : ";
		cin >> x;

		if (x != 0)
		{
			s = new dnode;
			s->data = x;
			cout << x << endl;

			p->next = s;
			s->pre = p;
			p = s;
		} 
		else
		{
			cycle = 0;
		}
	}

	head = head->next;
	head->pre = NULL;
	p->next = NULL;

	//cout << "Head data of dnode is " << head->data << endl;
	return head;
}

//链表插入
dnode *Insert(dnode *head, int num)
{
	dnode *p0, *p1;
	p0 = new dnode;
	p0->data = num;
	p1 = head;

	while (p0->data > p1->data && p1->next != NULL)
	{
		p1 = p1->next;
	}

	if (p0->data <= p1->data)
	{
		if (p1 == head)// 头节点插入
		{
			p0->next = p1;
			p1->pre = p0;
			head = p0;
		} 
		else//中间结点插入
		{
			p1->pre->next = p0;
			p0->next = p1;
			p0->pre = p1->pre; // 遗忘点
			p1->pre = p0;
		}
	} 
	else// 尾部插入结点
	{
		p1->next = p0;
		p0->pre = p1;
		p0->next = NULL;
	}
	return head;
}

// 双链表删除
dnode *del(dnode *head, int num)
{
	dnode *p1;
	p1 = head;

	while (num != p1->data && p1->next != NULL)
	{
		p1 = p1->next;
	}

	if (p1->data == num)
	{
		if (p1 == head)//首结点 head head->next 
		{
			head = head->next;
			head->pre = NULL;
			delete p1;
		} 
		else
		{
			if (p1->next == NULL)// 尾节点 p1->pre  p1  NULL
			{
				p1->pre->next = NULL;
				delete p1;
			} 
			else//中间结点
			{
				p1->next->pre = p1->pre;
				p1->pre->next = p1->next;
				delete p1;
			}
		}
	} 
	else
	{
		cout << "Please check out the data !" << endl;
	}
	return head;
}

// 打印双链表
void PrintDL(dnode *head)
{
	dnode *p = head;
	int l = 0;

	while (p != NULL)
	{
		p = p->next;
		l++;
	}
	cout << "The length of dnode is " << l << endl;

	p = head;
	for (int i = 0; i < l; i++)
	{
		cout << "The dnode data is " << p->data << endl;
		p = p->next;
	}

}

int main()
{
	cout << "****创建双链表****" << endl;
	dnode *head = creat();
	cout << endl;

	cout << "****双链表测长和打印****" << endl;
	PrintDL(head);
	cout << endl;

	cout << "***双链表插入数据***" << endl;
	cout << "Please input the int data for ins operate : ";
	int Indata1 = 0;
	cin >> Indata1;
	head = Insert(head, Indata1);
	PrintDL(head);
	cout << endl;

	cout << "***双链表删除数据***" << endl;
	cout << "Please input the int data for del operate : ";
	int Indata2 = 0;
	cin >> Indata2;
	head = del(head, Indata2);
	PrintDL(head);
	cout << endl;

	return 0;
}

1.头结点插入和删除

双链表的创建、测长、打印、插入和删除_第1张图片

2.中间结点插入和删除

双链表的创建、测长、打印、插入和删除_第2张图片

3.尾结点插入和删除

双链表的创建、测长、打印、插入和删除_第3张图片

你可能感兴趣的:(C++,链表,struct,typedef)