Remove Nth Node From End of List

来源:互联网 发布:做假章的软件 编辑:程序博客网 时间:2024/06/14 03:55
  • Given a linked list, remove the nth 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.


    主要考察链表指针的操作以及对边界异常情况的处理,C++代码如下:

class Solution {public:    ListNode *removeNthFromEnd(ListNode *head, int n) {    ListNode *pNodeOne = head, *pNodeTwo = head;    while (pNodeTwo != NULL) {        pNodeTwo = pNodeTwo->next;        if (n-- < 0)             pNodeOne = pNodeOne->next;    }    if (n == 0)         head = head->next;    else         pNodeOne->next = pNodeOne->next->next;    return head;    }};
0 0
原创粉丝点击