尾插法新建链表
核心代码:
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 2024-05-06 16:40 Destiny9521 阅读(15) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端