您的位置:首页 > Web前端 > Node.js

LeetCode(19) Remove Nth Node From End of List

2015-08-08 16:38 225 查看

题目

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.

Note:

Given n will always be valid.

Try to do this in one pass.

分析

给定一个链表头结点与整数n,要求删除链表中倒数第n个结点,返回链表头结点。

题目不难,主要是必须考虑周全;

head==NULL || n==0,则直接返回head

链表中结点总数count < n,则直接返回head

链表中结点总数count == n,则head=head->next,返回head

删除中间或尾结点,即删除正序第count-n+1 个结点,将倒序改为正序处理

AC代码

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (head == NULL || n == 0 )
return head;

//计算链表中的结点个数
int count = 0;
ListNode *p = head;
while (p)
{
count++;
p = p->next;
}

//链表中的结点个数小于要删除的倒数第n个
if (count < n)
{
return head;
}
else if (count == n)
{
ListNode *tem = head;
head = head->next;
delete tem;
}
else{
ListNode *p = head, *q = p->next;
int i = 1;
while (i < (count - n) && q->next!=NULL)
{
p = p->next;
q = q->next;
i++;
}
p->next = q->next;
delete q;
}
return head;

}
};


GitHub测试程序源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: