标签:
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个结点,返回链表头结点。
题目不难,主要是必须考虑周全;
/**
* 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;
}
};
LeetCode(19) Remove Nth Node From End of List
标签:
原文地址:http://blog.csdn.net/fly_yr/article/details/47359743