1.求鏈表倒數第K個節點
ahead指針先走K-1步,behind指針開始走,ahead走到末尾,此時behind剛好是倒數第K個
2.求鏈表中間節點
ahead指針一次走2步,behind一次走1步,當ahead走到末尾時,behind剛好是中間節點
3.判斷鏈表是否成環
ahead指針一次走2步,behind一次走1步,當ahead走到末尾時,還沒有追上behind說明無環。如果沒有到末尾就遇上了,說明有環。
4.鏈表反轉
2個指針相鄰同步後移,不停後者next改指向前者
ListNode* reverseList(ListNode* head) { ListNode* result = NULL;//反轉後的頭節點 ListNode* cur = head; ListNode* pre = NULL; while(cur != NULL) { ListNode* next = cur->next;//覆蓋前先記錄舊值 if(next == NULL) { result = cur;//記錄尾節點 } cur->next = pre;//改變cur節點next指針指向前者 pre = cur; cur = next;//同步後移 } return result; }
5.鏈表合併
ListNode* mergeList(ListNode* head1, ListNode* head2) { if(head1 == NULL) return head2; else if(head2 == NULL) return head1; if(head1->data > head2->data) {//保證head1頭節點小於等於head2頭節點,合併後頭節點就是head1 int temp = head2->data; head2->data = head1->data; head1->data = temp; } ListNode* cur1 = head1; while(head2 != NULL)//依次將鏈表2節點插入鏈表1合適位置 { while(cur1->next != NULL && cur1->next->data < head2->data) cur1 = cur1->next; //此時cur1 <= head2 <= cur1->next或者cur1是尾節點但不大於head2,將head2插在cur後即可 ListNode* tmp = head2; head2 = head2->next; tmp->next = cur1->next; cur1->next = tmp; } return head1; }