链表专题
思路:新建一个temp节点,双指针后移
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode ReverseList(ListNode head) { if(head==null||head.next==null){ return head; } ListNode a=head; ListNode b=head.next; while(b!=null) { ListNode c=b.next; b.next=a; a=b; b=c; } head.next=null; return a; } }
思路:1、先将待反转的区域反转
2、把 pre
的 next
指针指向反转以后的链表头节点,把反转以后的链表的尾节点的 next
指针指向 succ
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseBetween(ListNode* head, int left, int right) { ListNode* dummy=new ListNode(-1); dummy->next=head; auto pre=dummy; for(int i=0;i<left-1;i++) { pre=pre->next; } auto cur=pre->next; auto leftNode=pre->next; for(int i=left;i<right;i++) { cur=cur->next; } auto next=cur->next; cur->next=NULL; pre->next=NULL; fun(leftNode); pre->next=cur; leftNode->next=next; return dummy->next; } void fun(ListNode* &head) { auto a=head; auto b=head->next; while(b) { auto c=b->next; b->next=a; a=b; b=c; } head->next=nullptr; } };
思路:
class Solution { public: ListNode* mergeTwoLists(ListNode *a, ListNode *b) { if ((!a) || (!b)) return a ? a : b; ListNode head, *tail = &head, *aPtr = a, *bPtr = b; while (aPtr && bPtr) { if (aPtr->val < bPtr->val) { tail->next = aPtr; aPtr = aPtr->next; } else { tail->next = bPtr; bPtr = bPtr->next; } tail = tail->next; } tail->next = (aPtr ? aPtr : bPtr); return head.next; } ListNode* merge(vector <ListNode*> &lists, int l, int r) { if (l == r) return lists[l]; if (l > r) return nullptr; int mid = (l + r) >> 1; return mergeTwoLists(merge(lists, l, mid), merge(lists, mid + 1, r)); } ListNode* mergeKLists(vector<ListNode*>& lists) { return merge(lists, 0, lists.size() - 1); } }; 作者:LeetCode-Solution 链接:https://leetcode-cn.com/problems/merge-k-sorted-lists/solution/he-bing-kge-pai-xu-lian-biao-by-leetcode-solutio-2/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。