题目:
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
基本思想:
定义三个指针,分别指向当前遍历到的节点,它的前一个节点以及后一个节点。
最后反转后链表的头结点,就是原始链表的尾节点。尾节点的next为NULL。
#include <iostream>
using namespace std;
typedef int ElemType;//数据类型模板
typedef struct Node//结点
{
ElemType data;
struct Node *next;
}Node;
typedef struct Node * LinkList;
//建表
Node* creat_Link(Node *head)
{
int x;
Node *p,*q;
head=(Node *)malloc(sizeof(Node));
head->next=NULL;
q=head;
cin>>x;
while(x!=999)
{
p=(Node *)malloc(sizeof(Node));
p->data=x;
p->next=NULL;
q->next=p;
q=p;
cin>>x;
}
return head;//建完表后返回头结点
}
//输出
void output_Link(Node * head)
{
if(head==NULL)
{
cout<<"空链表!"<<endl;
return;
}
Node *q;
q= head->next;
while(q!=NULL)
{
cout<<q->data<<" ";
q=q->next;
}
cout<<endl;
}
Node * foo(Node *head)
{
Node *pReverHead=NULL;
Node *pNode=head;
Node *pPrev=NULL;
while(pNode!=NULL)
{
Node * pNext=pNode->next;
if(pNext==NULL)
pReverHead=pNode;
pNode->next=pPrev;
pPrev=pNode;
pNode=pNext;
}
return pReverHead;
}
void main()
{
Node *head=NULL;
Node * pHead=creat_Link(head);//建表
cout<<"原链表为:";
output_Link(pHead);//输出
Node * result = foo(pHead);
cout<<"反转链表头结点为:";
cout<<result->data<<endl;
}