一、合并两个有序链表
【题目】206. 反转链表
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution 10 { 11 public: 12 ListNode* reverseList(ListNode* head) 13 { 14 if(!head) return head; 15 ListNode * curr = head->next; 16 head->next = nullptr; 17 while(curr) 18 { 19 ListNode *temp = curr->next; 20 curr->next = head; 21 head = curr; 22 curr = temp; 23 } 24 return head; 25 } 26 };
二、合并两个有序链表
【题目】21. 合并两个有序链表
1 /** 2 * 3 * Definition for singly-linked list. 4 * struct ListNode { 5 * int val; 6 * ListNode *next; 7 * ListNode(int x) : val(x), next(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) 13 { 14 if(!l1 && !l2) return nullptr; 15 else if(!l1) return l2; 16 else if(!l2) return l1; 17 18 ListNode node(0), *head = &node; 19 while(l1 && l2) 20 { 21 if(l1->val < l2->val) 22 { 23 head->next = l1; 24 head = l1; 25 l1 = l1->next; 26 } 27 else 28 { 29 head->next = l2; 30 head = l2; 31 l2 = l2->next; 32 } 33 } 34 35 if(l1) head->next = l1; 36 if(l2) head->next = l2; 37 38 return node.next; 39 } 40 };