剑指offer-面试题25-合并两个排序的链表-链表


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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
题目:
    输入两个递增排序的链表,合并这两个链表并使新的链表中的节点依然是递增排序。
    返回新链表的头节点。
*/
/*
思路:
    1、返回的链表的头节点为两个链表中头节点数值更小的为链表1。
    2、进行比较
    3、判断链表2的节点是否为空,若不为空则全部加到链表1的尾部。
*/
#include <iostream>
#include<cstdlib>

using namespace std;

struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};

ListNode* Merge(ListNode* pHead1, ListNode* pHead2){
    if(pHead1 == nullptr) return pHead2;
    if(pHead2 == nullptr) return pHead1;
    ListNode* pNode = nullptr;
    ListNode* qNode = nullptr;
    ListNode* temp = nullptr;
    ListNode* head = nullptr;
    if(pHead1->val < pHead2->val){
        pNode = pHead1;
        qNode = pHead2;
        head = pHead1;
    }else{
        pNode = pHead2;
        qNode = pHead1;
        head = pHead2;
    }
    while(pNode->next != nullptr && qNode != nullptr){
        if(pNode->next->val <= qNode->val){
            pNode = pNode->next;
        }else{
            temp = pNode->next;
            pNode->next = qNode;
            qNode = qNode->next;
            pNode->next->next = temp;
        }
    }
    if(pNode->next == nullptr){
        pNode->next = qNode;
    }
    return head;
}

int main()
{
    ListNode *node6 = new ListNode(6);
    ListNode *node5 = new ListNode(5);
    ListNode *node4 = new ListNode(4);
    ListNode *pHead2 = new ListNode(1);
    ListNode *node3 = new ListNode(5);
    ListNode *node2 = new ListNode(2);
    ListNode *node1 = new ListNode(2);
    ListNode *pHead1 = new ListNode(0);
    pHead1->next = node1;
    node1->next = node2;
    node2->next = node3;
    node3->next = nullptr;
    pHead2->next = node4;
    node4->next = node5;
    node5->next = node6;
    node6->next = nullptr;

    ListNode* pHead = Merge(pHead1,pHead2);
    cout<<"answer"<<endl;
    while(pHead != nullptr){
        cout<<pHead->val<<endl;
        pHead = pHead->next;
    }


    cout << "Hello world!" << endl;
    return 0;
}