LeetCoder_____Remove Nth Node From End of List(11)

来源:互联网 发布:linux 删除命令 编辑:程序博客网 时间:2024/06/14 03:30

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.

题意:

给出一个链表,删除倒数第n个节点。


分析:

两个指针p1,p2,一个指针p1先走n步,然后同时一起走,当p1为NULL,删除p2所处节点即可。

在面试中出现这种题目需要注意一些地方:(程序的鲁棒性)

1.给出的head指针为NULL。

2.给出的n为非正数。

3.给出的n超过链表的长度。

4.当删除的节点为头节点或者尾节点。


代码:

class Solution {public:    ListNode* removeNthFromEnd(ListNode* head, int n) {        if(head == NULL || n == 1 && head->next == NULL) return NULL;        if(n <= 0)return head;        ListNode* p1,*p2;        p1 = p2 = head;        if(n == 1){            while(p1->next->next != NULL)                p1 = p1->next;            p1->next = NULL;            return head;        }        for(int i = 0 ; i < n ; i ++){            if(p1 == NULL) return head->next;            p1 = p1->next;        }        while(p1 != NULL){            p1 = p1->next;            p2 = p2->next;        }        p2->val = p2->next->val;        p2->next = p2->next->next;        return head;    }};











0 0