首页 > 代码库 > 单链表逆置

单链表逆置

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

 

#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;

}

 

单链表逆置