Delete the bottom-count K-node in a linked list

Source: Internet
Author: User

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

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.