1. Description of the problem
Given a single linked list, delete its Countdown k node. For example, given a linked list: 1 → 2 → 3 → 4 → 5 , delete its second-to-last node and change to 1 → 2 → 3 → 5 。 It can be assumed that the reciprocal K-node is always present.
2. Methods and Ideas
It is easy to think of the first method, that is, a single-linked list of the first traversal, to find its length n. Then the second traversal, set a pointer, move backwards n? k Location, and then delete the node.
The second approach is to use a double pointer, which only needs to be accessed over the linked list.
I. ListNode *p=*q=head
II. Q-pointer moves back to K-position
Iii. while Q! = End
P,q simultaneous back shift
Iv. removing the next node of P
ListNode* Removenthfromend (ListNode* head, int n) {ListNode*pre=head,*End=head; while(n--)End=End-Next; while(End&&End-Next) Pre = Pre->Next,End=End-Next;if(End==NULL)returnHead->Next;Else{ListNode*tmp = pre->Next; Pre->Next= tmp->Next; Delete tmp; }returnHead }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Delete the bottom-count K-node in a linked list