Remove nth node from end of list

Source: Internet
Author: User

This problem can be solved using the double pointer method. The distance between the two pointers p and q is kept at N-1, and then the Q is moved to the last element of the list, then P points to the nth node from the end. To delete this node, there are two cases: one is that the node is the head, and the other is the intermediate node. In the first case, you can simply use the following operations: Head = head-> next. In the second case, we need to introduce an additional pointer prev_p pointing to the previous node of P, so that the node can be deleted through prev_p-> next = prev_p-> next. The Code is as follows:

1 class solution {2 public: 3 listnode * removenthfromend (listnode * head, int N) {4 listnode * P = head, * q = head, * prev_p = NULL; 5 For (INT I = 0; I <n-1; I ++) 6 q = Q-> next; 7 for (; q-> next; q = Q-> next, prev_p = P, P = p-> next); 8 If (P = head) Head = head-> next; 9 else 10 prev_p-> next = p-> next; 11 return head; 12} 13 };

 

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.