Delete the last k nodes and the last node in the linked list.
1. Problem Description
Given a single-chain table, delete its last k nodes. For example, the given linked list: 1 → 2 → 3 → 4 → 5 , Delete the second to last node and change 1 → 2 → 3 → 5 . It can be assumed that the last k nodes always exist.
2. methods and ideas
It is easy to think of the first method, that is, first traverse a single-chain table and find its length n. Then perform the second traversal and set a pointer to move backward. N−k And then delete the node.
The second method is to use dual pointers. You only need to access the linked list once.
I. ListNode * p = * q = head
II. q pointer move k positions behind
III. while q! = End
P and q move back at the same time
IV. Delete 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) return head-> next; else {ListNode * tmp = pre-> next; pre-> next = tmp-> next; delete tmp;} return head ;}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.