单链表逆置

Posted xshang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单链表逆置相关的知识,希望对你有一定的参考价值。

重写单链表逆置,熟能生巧~

 

#include <iostream>
#include <cstdlib>

using namespace std;

typedef struct List{

    int num;
    struct List *next;

}ListNode,*pListNode;

void display(ListNode *pHead)
{

    while(pHead)
    {
        cout<<pHead->num<<"--";
        pHead = pHead->next;
    }

    cout<<endl;
}

ListNode* ReverseListNode(ListNode *pHead)
{
    ListNode* curNode = pHead;
    ListNode* preNode = pHead->next;
    ListNode* nextNode = preNode->next;
    curNode->next = NULL;
    while(nextNode)
    {
        preNode->next = curNode;
        curNode = preNode;
        preNode = nextNode;
        nextNode = nextNode->next;
    }

    preNode->next = curNode;

    return preNode;
}


int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    ListNode* pHead = (struct List*)malloc(sizeof(struct List));
    pHead->num = 0;
    pHead->next = NULL;

    for(int i = 0; i < 10; i++)
    {
         ListNode *pNode = (struct List*)malloc(sizeof(struct List));
         pNode->num = arr[i];
         pNode->next = NULL;

         pNode->next = pHead->next;
         pHead->next = pNode;

    }

    ListNode* pTemp = pHead;

    while(pTemp)
    {
        cout<<pTemp->num<<"--";
        pTemp = pTemp->next;
    }

    cout<<endl;
    ListNode* pTemp2 = ReverseListNode(pHead);
    while(pTemp2)
    {
        cout<<pTemp2->num<<"--";
        pTemp2 = pTemp2->next;
    }

    cout<<endl;

    return 0;

}

 

以上是关于单链表逆置的主要内容,如果未能解决你的问题,请参考以下文章

单链表逆置

03 单链表逆置

单链表逆置

单链表逆置

单链表类,链表逆置

对于"单链表逆置和递归"的问题的理解.