Problem:
Given A linked list, remove the nth node from the end of the list and return its head.
For example,
1->2->3->4->5 N = 2. 1->2->3->5.
Note:
Given n would always be valid.
Try to do the in one pass.
Solution: In the way of a cursor, a cursor s in the position of the front N, another p in the head, when s go to the end of the list when the P position is the place to be deleted, time complexity O (n)
To give a single linked list, ask to delete the number of the count of the nth.
Java source Code (308MS):
/** * 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) { listnode s,p=new listnode (0); S=head;p.next=head; while (n>0 && s!=null) { s=s.next; n--; } while (s!=null) { s=s.next; P=p.next; } if (p.next==head) { head=head.next; } else{ p.next=p.next.next; } return head; }}
C Language Source code (6MS):
/** * Definition for singly-linked list. * struct ListNode {* int val; * struct ListNode *next; *}; */struct listnode* removenthfromend (struct listnode* Head, int n) { struct listnode *s,*p= (struct listnode*) malloc (sizeof (struct listnode)); s=head;p->next=head; while (n--&& s!=null) s=s->next; while (s!=null) { s=s->next; p=p->next; } if (p->next==head) { head=head->next; } else{ p->next=p->next->next; } return head;}
C + + source code (8MS):
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public: listnode* removenthfromend (listnode* head, int n) { listnode *s,*p=new listnode (0); s=head;p->next=head; while (n--&& s!=null) s=s->next; while (s!=null) { s=s->next; p=p->next; } if (p->next==head) { head=head->next; } else{ p->next=p->next->next; } return head; };
Python source code (67MS):
# Definition for singly-linked list.# class listnode:# def __init__ (self, x): # self.val = x# Self.next = Nonec Lass Solution: # @param {ListNode} head # @param {integer} n # @return {listnode} def removenthfromend ( Self, head, N): s=head;p=listnode (0) P.next=head while n>0 and S!=none: n-=1;s=s.next While S!=none: s=s.next;p=p.next if P.next==head:head=head.next else:p.next=p.next.next Return head
Leetcode Remove Nth Node from End of List (C,c++,java,python)