(链表) leetcode 21. Merge Two Sorted Lists

mac2022-06-30  73

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 中文:将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 ----------------------------------------------------------------------------------------------------------------- 这是一个链表操作的基础题,就是注意要分配一个空间来建立一个头结点C++代码 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode *dummy = new ListNode(-1),*cur = dummy; //* dummy是分配空间的,必须要分配空间,这个才能会得到一个结点,cur只是一个辅助结点(指针?)而已,并没有分配空间。 while(l1 && l2){ if(l1->val < l2->val){ cur->next = l1; l1 = l1->next; } else{ cur->next = l2; l2 = l2->next; } cur = cur->next; } cur->next = l1 ? l1:l2; //就是如果l1和l2中长度更小的遍历完后,长度更大的剩下的就由cur链接它。 return dummy->next; } };

 

转载于:https://www.cnblogs.com/Weixu-Liu/p/10703967.html

最新回复(0)