Remove nth node from end of list

Source: Internet
Author: User

Given a linked list, removeNTh node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
GivenNWill always be valid.
Try to do this in one pass.

1/** 2 * definition for singly-linked list. 3 * struct listnode {4 * int val; 5 * listnode * Next; 6 * listnode (int x): Val (x), next (null) {} 7 *}; 8 */9 class solution {10 public: 11 listnode * removenthfromend (listnode * head, int N) {12 if (! Head | n <1) return head; // if the head is empty, or N is invalid, 13 listnode node (0); // you can delete 14 nodes by setting the header node. next = head; 15 listnode * pre = & node; // The Slow precursor node 16 listnode * fast = head; 17 while (N & fast) {// point fast to the nth node 18 fast = fast-> next; 19 -- N; 20} 21 if (N &&! Fast) return head; // if the length of the linked list is not greater than N, 22 listnode * slow = head; 23 while (FAST) {// fast and slow move at the same time, when slow is null, end 24 fast = fast-> next; 25 pre = slow; 26 slow = slow-> next; 27} 28 pre-> next = slow-> next; // Delete the nth node 29 delete slow; 30 return node. next; 31} 32 };

 

Set up the first and second pointers. Assume that the first pointer is fast and the last pointer is slow. First, let the fast pointer point to head, and then take n steps backward to point to the nth node. Then, the slow Pointer Points to head, let the fast pointer and the slow pointer move back at the same time, knowing that slow is null, then the fast Pointer Points to the last n nodes

 

Remove nth node from end of 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.