已知链表的表头为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;
}

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

被折叠的 条评论
为什么被折叠?



