编程之美读书笔记---单链表反序---要求只遍历一次

本文介绍了一个用于反转单链表顺序的C++函数实现。该函数仅需一次遍历即可完成链表元素的逆序排列,并附带了完整的示例代码及资源释放处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

扩展问题:

编写一个函数,给定一个链表的头指针,要求只遍历一次,将单链表中的元素顺序反序。

#include <iostream>
#include <string>
#include <algorithm>
#include <cstring>
using namespace std;
struct node{
	int data;
	node *next;
};
void reverselist(node* &head)
{
	node *p,*q;
	p=head->next;
	q=head->next->next;
	if(q==NULL)return;  //若链表只有一个元素,则不操作 
	p->next=NULL;
	while(q->next!=NULL)
	{
		node *tmp=q->next;
		q->next=p;
		p=q;
		q=tmp;
	
	}
	q->next=p;
	head->next=q; //将表头指针调转 
}
void destroy(node* &head)
{
	node *p=head;
	head=head->next;
	while(head->next!=NULL)
	{
		delete p;
		p=head;
		head=head->next;
	}
	delete p;
	delete head;
} 
int main()
{
	node *head=new node;
	head->next=NULL;
	int n;
	cin>>n;
	while(n--)
	{
		
		node *pt=new node;
		cin>>pt->data;
		pt->next=head->next;
		head->next=pt;
	}
	reverselist(head); //此时简历的链表是输入的逆序,所以倒序后成为输入的正序 
	
	node *pt=head->next;
	while(pt->next!=NULL)
	{
		cout<<pt->data<<" ";
		pt=pt->next;
	}
	cout<<pt->data<<endl;
	destroy(head);      //记得资源回收 
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值