尾插法新建链表

核心代码:

tail = head;  
s->next = NULL;  
tail->next = s;  
tail = s;

插入过程演示:

![[Pasted image 20230623143820.png]]

头插法尾插法新建链表完整代码

#include <iostream>
#include<malloc.h>
using namespace std;

typedef int Elemtype;
typedef struct LNode {
	Elemtype data;
	struct LNode* next;
}LNode,*LinkList;
void link_head_list(LinkList& head)
{
	head = (LinkList)malloc(sizeof(LNode));
	head->next = NULL;
	LNode* NewNode;
	int element;
	cin >> element;
	while (element != -1)
	{
		NewNode = (LinkList)malloc(sizeof(LNode));
		NewNode->data = element;
		NewNode->next = head->next;
		head->next = NewNode;
		cin >> element;
	}
}
void link_tail_list(LinkList& head)
{
	head = (LinkList)malloc(sizeof(LNode));
	head->next = NULL;
	LNode* NewNode, * tail;
	int element;
	tail = head;
	cin >> element;
	while (element != -1)
	{
		NewNode = (LinkList)malloc(sizeof(LNode));
		NewNode->data = element;
		NewNode->next = NULL;
		tail->next = NewNode;
		tail = NewNode;
		cin >> element;
	}
	
	tail->next = NULL;
}
void printlink(LinkList& L)
{
	L = L->next;
	while (L != NULL)
	{
		cout << L->data << " ";
		L = L->next;
	}
}
int main()
{
	LinkList A, B;
	cout << "请输入链表A,以-1结尾:";
	link_head_list(A);
	cout <<endl<<"以头插法建立的该链表为:";
	printlink(A);
	cout <<endl<< "请输入链表B,以-1结尾:";
	link_tail_list(B);
	cout <<endl<< "以头插法建立的该链表为:";
	printlink(B);
	return 0;
}

posted on   Destiny9521  阅读(15)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示