标签:
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.
Linked List Two Pointers
这道题题目要求删除链表中指定的倒数第n个结点,并且采用一次遍历,所以应该采用两个指针的方法
先将指针ptr1和ptr2之间的距离弄成n,再往后同时后移,而由于涉及到结点的删除,还要弄一个指针指到ptr1的前面那个结点处就可以了,
这道题要考虑到结点删除时是尾结点还是头结点还是中间结点
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *ptr1,*ptr2,*ptr0;
ptr0=head;
ptr1=head;
ptr2=head;
int N=n-1;
while(N--)
ptr2=ptr2->next;
if(ptr2->next==NULL)
if(ptr1->next!=NULL)
return ptr1->next;
else
return NULL;
ptr1=ptr1->next;
ptr2=ptr2->next;
while(ptr2->next!=NULL)
{ptr2=ptr2->next;ptr1=ptr1->next;ptr0=ptr0->next;}
if(n==0)
{ptr1->next=NULL;return head;}
ptr0->next=ptr1->next;
return head;
}
int main()
{
}
leetcode_19题——Remove Nth Node From End of List(链表)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4532619.html