尾插法新建链表

核心代码:

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  阅读(54)  评论(0)    收藏  举报

导航