leetcode 常用链表操作
/** * 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) {} * }; */
//快慢指针,获得中点 ListNode* getmid(ListNode* head){ ListNode* fast=head,*slow=head; while(fast->next&&fast->next->next){ fast=fast->next->next; slow=slow->next; } return slow; }
//迭代,反转链表 ListNode* reverse(ListNode *head){ ListNode* cur=head,* pre=nullptr; while(cur){ ListNode* temp=cur->next; cur->next=pre; pre=cur; cur=temp; } return pre; }
//合并 void merge(ListNode* l1,ListNode* l2){ ListNode*t1,*t2; while(l1&&l2){ t1=l1->next; t2=l2->next; l1->next=l2; l1=t1; l2->next=l1; l2=t2; } }
//将链表head切掉前n个节点,返回后半部分链表头 ListNode* cut(ListNode* head, int n) { auto p = head; while (--n && p) { p = p->next; } if (!p) return nullptr; auto next = p->next; p->next = nullptr; return next; }
//有序合并 ListNode* merge(ListNode* l1, ListNode* l2) { ListNode dummyHead(0); auto p = &dummyHead; while (l1 && l2) { if (l1->val < l2->val) { p->next = l1; p = l1; l1 = l1->next; } else { p->next = l2; p = l2; l2 = l2->next; } } p->next = l1 ? l1 : l2; return dummyHead.next; }