1.设置表头节点dummy的作用:统一循环内的操作;如果仅仅使用头指针head,则无法做到统一,必须单独写一个if判断。
2.使用已知的两个链表头指针l1、l2作为双指针
3.从dummy节点出发,每次比较l1->val和l2->val的大小,小的被链接到rear上
4.这种方法并没有破坏原有的两个链表,而是直接把他们拼接成了一个,既不用新开辟储存空间,也不用释放原来的空间。
LinkCode题165:“合并两个排序链表”:
1 /** 2 * Definition of singly-linked-list: 3 * class ListNode { 4 * public: 5 * int val; 6 * ListNode *next; 7 * ListNode(int val) { 8 * this->val = val; 9 * this->next = nullptr; 10 * } 11 * } 12 */ 13 14 class Solution { 15 public: 16 /** 17 * @param l1: ListNode l1 is the head of the linked list 18 * @param l2: ListNode l2 is the head of the linked list 19 * @return: ListNode head of linked list 20 */ 21 ListNode * mergeTwoLists(ListNode * l1, ListNode * l2) { 22 // write your code here 23 ListNode q=ListNode(0); 24 ListNode* dummy=&q;/*由于要求返回头指针,故将表头节点dummy创建在栈上避免内存泄漏*/ 25 ListNode* rear=dummy; 26 while(l1!=nullptr&&l2!=nullptr){ 27 if(l1->val<l2->val){ 28 rear->next=l1; 29 l1=l1->next; 30 }else{ 31 rear->next=l2; 32 l2=l2->next; 33 } 34 rear=rear->next; 35 } 36 rear->next=l1==nullptr?l2:l1; 37 return dummy->next; 38 } 39 };