将链表逆序操作

本文介绍了一种使用C语言实现链表逆序的方法。通过逆插入的方式,文章提供了一个具体的函数实现示例,并展示了如何创建链表并进行逆序操作。此外还提供了完整的程序代码,演示了输入字符串创建链表及逆序前后的输出。

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

已知链表的表头为head,写一个函数将链表逆序操作。

采用逆插入的方法。

#include<iostream>
using namespace std;
typedef struct node
{
	char data;
	struct node *next;
}Node;
Node *Reverse(Node *head)
{
	Node *temp=(Node*)malloc(sizeof(Node));
	Node *p=(Node*)malloc(sizeof(Node));
	temp->next=NULL;
	if (head==NULL||head->next==NULL)
	{
		return head;
	}
	while (head!=NULL)
	{
		p->data=head->data;
		p->next=temp->next;
		temp->next=p;
		head=head->next;
		p=(Node*)malloc(sizeof(Node));
	}
	return temp->next;
}
int main(int argc,char *argv[])
{ 
	Node *head=(Node*)malloc(sizeof(Node));
	Node *h1,*h2,*k;
	Node *temp=(Node*)malloc(sizeof(Node));
	char ch;
	h1=h2=head;
	fflush(stdin);
	cout<<"请输入一行字符串:"<<endl;
	while ((ch=getchar())!='\n')
	{
		temp->data=ch;
		head->next=temp;
		head=temp;
		temp=(Node*)malloc(sizeof(Node));
	}
	head->next=NULL;
	h1=h1->next;
	cout<<"逆序之前:"<<endl;
	while (h1!=NULL)
	{
		cout<<h1->data;
		h1=h1->next;
	}
	cout<<endl;
	h2=h2->next;
	k=Reverse(h2);
	cout<<"逆序之后:"<<endl;
	while (k!=NULL)
	{
		cout<<k->data;
		k=k->next;
	}
	cout<<endl;
	free(head);
	free(temp);
	return 0;
}
	    


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值