/* 题目: 输入两个递增排序的链表,合并这两个链表并使新的链表中的节点依然是递增排序。 返回新链表的头节点。 */ /* 思路: 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; }