面试题16:反转链表

来源:互联网 发布:网络it需要什么学历 编辑:程序博客网 时间:2024/04/19 22:25
#include<iostream>using namespace std;struct Node{    int nValue;    Node *pNext;};void CreateList(Node **pHead,Node **pEnd,int n){    int nValue;    for(int i=0;i<n;i++)    {        cin>>nValue;        Node *temp = new Node;        temp->nValue = nValue;        temp->pNext = NULL;        if((*pHead) == NULL)        {            (*pHead) = temp;        }        else        {            (*pEnd)->pNext = temp;        }        (*pEnd) = temp;    }}Node* ReverseList(Node *pHead,Node *pEnd){    Node *pPrev = NULL;//记录前一个节点    Node *temp = pHead;//记录当前结点    Node *pNext = NULL;//记录下一个节点    Node *pReverseHead = NULL;//记录反转链表的头结点地址    while(temp)    {        pNext = temp->pNext;        if(pNext == NULL)        {            pReverseHead = temp;        }        temp->pNext = pPrev;//更改指针        pPrev = temp;//交替更换 pPrev  和 temp指针        temp = pNext;    }    return pReverseHead;}int main(){    int n;    while(cin>>n)    {        Node *pHead = NULL;        Node *pEnd = NULL;        CreateList(&pHead,&pEnd,n);        Node *temp = pHead;        while(temp)        {            cout<<temp->nValue<<" ";            temp = temp->pNext;        }        Node *ReverseHead = ReverseList(pHead,pEnd);        cout<<endl<<"--------------------------"<<endl;        while(ReverseHead)        {            cout<<ReverseHead->nValue<<" ";            ReverseHead = ReverseHead->pNext;        }    }    return 0;}
//递归版本
Node *Reverse_List(Node *pHead)
{
<span style="white-space:pre"></span>if(pHead == NULL || pHead->pNext == NULL)
<span style="white-space:pre"></span>{
<span style="white-space:pre"></span>return pHead;
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>Node *NewHead = Reverse_list(pHead->pNext);
        pHead->next->next = pHead;
<span style="white-space:pre"></span>pHead = pHead->pNext;
<span style="white-space:pre"></span>return NewHead;
}

1 0
原创粉丝点击