算法学习之旅,初级篇(27)-–逆转一个链表

来源:互联网 发布:乐福数据 编辑:程序博客网 时间:2024/06/06 18:09

介绍
定义一个函数,输入一个链表的头结点,反转该链表并输出反转链表的头结点。
分析
如果要反转链表,就要把next指针指向prev指针。所以移动时,需要保存next,prev以及当前的链表指针。
代码

#include<stdio.h>#include<iostream>#include<stdlib.h>using namespace std;typedef struct ListNode{    int value;    ListNode *next;}ListNode;//逆转链表ListNode* ReverseList(ListNode* pHead){    ListNode* pReverseList=NULL;    //当前节点    ListNode* pNode=pHead;    //前一个节点    ListNode* pPrev=NULL;    //下一个节点    ListNode* pNext=NULL;    while(pNode!=NULL)    {        pNext=pNode->next;        //翻转next        pNode->next=pPrev;        //向后移动        pPrev=pNode;        pNode=pNext;    }    return pPrev;}int main(){    ListNode* m_a =(ListNode*)malloc(sizeof(ListNode));    m_a->value=10;    m_a->next=NULL;    ListNode* a1=m_a;    for(int i=10;i<15;i++)    {        ListNode* b=(ListNode*)malloc(sizeof(ListNode));        b->value=i*2;        b->next=NULL;        a1->next=b;        a1=b;    }    a1=m_a;    while(a1!=NULL)    {        cout<<a1->value<<" ";        a1=a1->next;    }    cout<<endl;    ListNode* k=ReverseList(m_a);    while(k!=NULL)    {        cout<<k->value<<" ";        k=k->next;    }    system("pause");    return 0;}

遇到的问题
注意指针移动。和指针的改变顺序。