您的位置:首页 > 其它

删除单链表的倒数第N个节点

2015-04-14 14:23 239 查看


容易 删除链表中倒数第n个节点
查看运行结果

37%

通过

给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。

注意

链表中的节点个数大于等于n

样例

给出链表1->2->3->4->5->null和 n = 2.
删除倒数第二个节点之后,这个链表将变成1->2->3->5->null.

挑战

O(n)时间复杂度

/**
* Definition of ListNode
* class ListNode {
* public:
*     int val;
*     ListNode *next;
*     ListNode(int val) {
*         this->val = val;
*         this->next = NULL;
*     }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
int length(ListNode *head) {
ListNode *p = head;

int l=0;
while(p != NULL) {
p = p->next;
l++;
}
return l;
}
ListNode *removeNthFromEnd(ListNode *head, int n) {
// write your code here
int length = this->length(head);
if(length==0) {
return NULL;
}
if(length ==n){
return head->next;
}
n = length-n;
ListNode *p = head;
ListNode *q =head;
int i = 0;
while (q != NULL && i < n) {
q=p;
p=p->next;
i++;
}
q->next = p->next;
delete p;
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: