The 19th question of 2018.9.30 Leetcode brush question Diary

Source: Internet
Author: User

Tag: Suppose code establishes the node from Val question Rem end

The task is more classic, in the case of a single-link list to complete the end of the nth node Delete:

Set up three nodes:

Cur record the current node location.

Ans Record the first of the nodes to be deleted

H record the table header position of the linked list

Assuming that you want to delete the nth point (which ensures that the deletion is valid), the ANS node should go to the last n+1 node in order to delete the bottom 3rd node directly cur.

The ANS is cur to walk the N nodes only to leave, to ensure that cur to the end of the list traversal, Ans.next point to delete the node

Finally, return the header h that deletes the node.

Program AC, but there is a case, that is, if the length of the list of N, delete the last nth point, the original algorithm will always fail, only for the case use return h.next, and do not want to understand

The procedure is as follows:

/**
* Definition for singly-linked list.
* Public class ListNode {
* int val;
* ListNode Next;
* ListNode (int x) {val = x;}
* }
*/
Class Solution {
Public ListNode Removenthfromend (listnode head, int n) {
if (Head.next = = null) {
return null;
}
ListNode cur = new ListNode (0);
ListNode ans = new ListNode (0);
cur = head;
Ans.next = head;
int count = 1;
while (cur! = null) {
if (Count > N) {
ans = ans.next;
}
cur = cur.next;
Count + +;
}
if (Ans.next = = head) return head.next; Ans Does not move, the list of length n is deleted from the last nth node, using the delete in else is invalid
else{
Ans.next = Ans.next.next;
return head;

}
}
}

The 19th question of 2018.9.30 Leetcode brush question Diary

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.