遍历链表,将节点接到末端 【1月16日学习笔记】

点击查看代码
//遍历链表,将节点接到末端                                                                          
#include<iostream>
using namespace std;
 
struct node
{
	int data;//数据
	node* next;//尾巴
};//定义节点结构体
node* A;//头指针固定,global variable,can be accessed anywhere
 
int main()
{   
 
	A = NULL;//empty list
 
	node* temp = new node;//创建新节点,并创建temp指针指向新节点
	(*temp).data = 2;//节点赋值
	(*temp).next = NULL;//新节点尾巴赋空
	A = temp;//头指针指向新节点(temp指向新节点,指向复制)
 
	temp = new node;//创建新节点,并将temp指针指向新节点
	(*temp).data = 4;//节点赋值
	(*temp).next = NULL;//新节点尾巴赋空
 
	node* run = A;
	while ((*run).next != NULL)
	{
		run = (*run).next;
	}//用遍历指针扫描至指向已建立链表末节点,即结束时run指向末节点
 
	(*run).next= temp;//末节点尾巴指向新节点                      
	                       
 
	temp = new node;//创建新节点,并将temp指针指向新节点
	(*temp).data = 8;//节点赋值
	(*temp).next = NULL;//新节点尾巴赋空
 
	run = A;
	while ((*run).next != NULL)
	{
		run = (*run).next;
	}//用遍历指针扫描至指向已建立链表末节点
 
	(*run).next = temp;//末节点尾巴指向新节点
 
	run = A;
	while (run!= NULL)
	{
		cout << (*run).data << " ";
		run = (*run).next;
	}
	cout << endl;//用遍历指针扫描至指向NULL,顺序打印节点值
}
posted @ 2024-01-17 09:17  bituion  阅读(22)  评论(0)    收藏  举报