剑指offer反转链表

时间:2024-12-02 11:34:43
剑指offer反转链表

way1:
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
37
38
39
40
41
42
43
/*struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode *p1,*p2,*p3;
        if(NULL!=pHead)
            p1=pHead;
        else
            return NULL;
        if(NULL!=p1->next)
            p2=p1->next;
        else
            return p1;
        if(NULL!=p2->next)
        {
            p3=p2->next;
            p1->next=NULL;
        }
        else
        {
            p1->next=NULL;
            p2->next=p1;
            return p2;
        }
          
        while(NULL!=p3->next)
        {
            p2->next=p1;
            p1=p2;
            p2=p3;
            p3=p3->next;                                  
        }
        p3->next=p2;
        p2->next=p1;
        return p3;
    }
};

way2:
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
/*struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode* p1=NULL;
        ListNode* p2=pHead;
        ListNode* p3=NULL;
        ListNode* newHead=NULL;
        while(NULL!=p2)
        {
            p3=p2->next;
            if(NULL==p3)
                newHead=p2;
            p2->next=p1;
            p1=p2;
            p2=p3;
        }
        return newHead;
    }
};