您的位置:首页 > 其它

leetcode19

2015-10-06 22:16 204 查看
LeetCode19 --------Remove Nth Node From End of List

链表操作。

我的思路是:

1.先计算出链表的长度len,再根据其求出要删除的元素的正序。

2.考虑头结点的操作。

代码:

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
		ListNode*ptr1 = head;
		int count =1;
		while(ptr1->next != NULL)
		{
			ptr1 = ptr1->next;
			count ++;
		}
		n= count - n;
		if(n == 0)
		{
			ptr1=head;
			head=head->next;
			delete ptr1;
			return head;
		}
		ptr1 = head;
		ListNode*ptr2=head;
		while(n --)
		{
			ptr1= ptr1->next;
		}
		while(ptr2!=ptr1&&ptr2->next != ptr1)
		{
			ptr2=ptr2->next;
		}
		ptr2->next = ptr1->next;
		delete ptr1;
		return head;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: