"Leetcode" 19. Remove Nth Node from End of List

Source: Internet
Author: User

Topic:

Idea: If the list is empty or n is less than 1, return directly, otherwise, let the list go from head to tail, each move one step, let N minus 1.

1. List 1->2->3,n=4, there is no fourth node, return the entire list

Swept nodes in sequence:

n Worth changing: 3-2-1

2. Linked list 1->2->3,n=3

Swept nodes in sequence:

n Worth changing: 2-1-0

3. Linked list 1->2->3,n=2

      Swept nodes in sequence:

      n Worth changing: 1-0--1

When walking to the end of the list: 1.n>0, indicating that the list does not have the nth node, directly return to the original linked list;

2.n=0, indicating that the last nth node of the list is the head node, returning to the Head.next;

3.n<0, start from the beginning, do not move one step to let N plus 1, when the n=0, move stop, the current move to the node is to delete the node's previous node. Because if the list length is L, then the previous node of the nth-L-n is the second. When the first sweep to the end of the list, the value of n becomes n-l, and when N is added 1 until 0 o'clock, the second sweep is exactly the first l-n node.

/** * Definition for singly-linked list. * public class ListNode {*     int val; *     ListNode Next; *     listnode (int x) {val = x;}}} */public class Soluti On {public    ListNode removenthfromend (listnode head, int n) {        if (head==null| | n<1) {            return head;        }         ListNode Cur=head;         while (cur!=null) {             n--;             Cur=cur.next;         }         if (n==0) {             return head.next;         }         if (n<0) {             cur=head;             while (++n!=0) {//When n=0 moves stop, the node moved to is the previous node to delete the node                 cur=cur.next;             }             Cur.next=cur.next.next;         }         return head;    }}

  

"Leetcode" 19. 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.