代码题(4)— 反转链表

题目:反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead == nullptr || pHead->next == nullptr)
            return pHead;
        ListNode* cur = pHead;
        ListNode *pre = nullptr, *nex = nullptr;
        while(cur != nullptr)
        {
            nex = cur->next;
            cur->next = pre;
            pre = cur;
            cur = nex;
            
        }
        return pre;
    }
};

猜你喜欢

转载自www.cnblogs.com/eilearn/p/9206241.html