Delete the last k nodes and the last node in the linked list.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.