C++单链表的操作(创建,删除,打印,遍历,插入)

时间:2023-01-06 21:42:41

其实C++中单链表中对数据的操作很好理解的,只要熟悉这个过程 头结点与中介结点的连接,以及中介结点与下一结点的连接,并把它带到下一次循环中,就创建成功了。而删除操作就更简单了,只需要使删除结点的前一结点的next域指向下一结点,在delet释放内存空间,就删除成功了,接下来遍历创建新结点都是一个原理,并不难理解

下面是我的实验代码:建立一个单链表 21 23 25 27 29 31,并输出该链表;

进行输入操作查找为n的结点,并输出;

进行输入X值查找为X的结点,并输出;

输入入序号N和值X,在序号N结点后插入,并输出链表;

删除结点,删除序号为N的结点。

#include <iostream>
#include <stdlib.h>
#include <malloc.h>
#define N 6
using namespace std;
struct node{
	int data; node *next;
};
node *Create(node *head);
void print(node *h);
node *find_data(node *head, int i);
int find_node(node *head, int x);
node *inset_node(node *head,int n, int x);
void insert_list(node *head, int n, int x);
void deleta_list(node *head, int n);
int main()
{
	node *list; int n; int x;
	list = NULL;
	//cout << "请输入链表的长度:" << endl;
	list = Create(list);
	print(list);
	cout << "请输入查找的序号:";
	cin >> n;
	cout << "输出值:"<< find_data(list, n)->data << endl;
	cout << "请输入值:";
	cin >> x;
	if(find_node(list, x))
		cout << "输出序号:" << find_node(list, x) << endl;
	else cout << "没有这个值!" << endl;
	insert_list(list, n, x);
	cout << "输出链表:";
	print(list);
	cout << "删除结点:"; cin >> n;
	deleta_list(list,n);
	cout << "输出链表:";
	print(list);
	
}
node *Create(node *head)
{
	node  *last, *p = NULL;
	head = (node*)malloc(sizeof(node));//建立为表头结点
	head->next = NULL;//将next域置空
	last = head;//last为指向尾节点的指针
	int k = 21;
	for (int i = 0; i < N; i++)
	{
		p = (node*)malloc(sizeof(node));
		//p->next = NULL;
		 p->data=k;
		last->next = p;//last->p  head->last last->p
		last = p;//为下一次循环做准备
		//p = p->next;
		p->next = NULL;
		k += 2;
	}
	return head;
}

void print(node *head)
{
	const node *p;
	p = head;
	p = p->next;

	while (p != NULL)
	{
		cout << p->data << "->";
		p = p->next;
	}
	cout << endl;
}
node *find_data(node *head, int i)
{
	node *p = head;
	int j=0;
	if (i <= 0)return NULL;
	while (j < i)
	{
		p = p->next;
		j++;
	}
	return p;
}
int find_node(node *head, int x)
{
	node *p = head;
	int j = 0;
	while (p->next)
	{
		p = p->next;
		j++;
		if (p->data == x)
			return j;
	}
	return 0;
}
void insert_list(node *head, int n, int x)
{
	int i = 0;
	node *p = head, *pNew,*q;
	cout << "插入结点:";
	cin >> n >> x;
	while (NULL != p && i<n)//找出这个结点的位置 
	{
		p = p->next;
		++i;
	}
	pNew= (node*)malloc(sizeof(node));
	pNew->data = x;  //给新节点的数据域赋值
	//p->next = pNew;
	q = p->next;//讲p->next赋值给q 即声明q为p的后一结点
	p->next = pNew;//将pnew的地址赋值给P的next域  即p指向pNew
	pNew->next = q;   // pNew = q;这里是更新新节点的指针域

}
void deleta_list(node *head, int n)
{
	int i = 0;
	node *p = head, *pdel,*q;
	while (p != NULL&&i < n-1)
	{
		p = p->next;
		i++;
	}
	pdel = p->next;
	q = pdel->next;
	p->next = q;
	delete(pdel);
}