反转链表

要求

将一个链表反转,例如:1->2->3->4-NULL 反转后为 4->3->2->1->NULL

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
using namespace::std;
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {

    }
};
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        //记得判断
        if (head==NULL||head->next==NULL) {
            return head;
        }

        //翻转链表固定模式
        ListNode* pre = head;
        ListNode* p = head->next;
        ListNode* next  = NULL;
        while (p!=NULL) {
            next = p->next;
            p->next = pre;
            pre = p;
            p = next;
        }
        head->next = NULL;
        return pre;
    }
};
int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
    return 0;
}

Comments