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个节点,设置两个节点指针ptr1和ptr2,它们之间相差n个节点,然后将指针往下移动,当ptr2的下一个节点为NULL时,ptr1就指向了删除节点的前一个节点。
特殊情况测试用例:
[1],1
[1,2],1
[1,2],2
C语言实现:
-
/**
-
* Definition for singly-linked list.
-
* struct ListNode {
-
* int val;
-
* struct ListNode *next;
-
* };
-
*/
-
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
-
if(NULL == head )
-
return NULL;
-
struct ListNode *ptr1,*ptr2,*tmp = NULL;
-
int i;
-
ptr1 = head;
-
ptr2 = head;
-
for(i=0;i<n;i++)
-
{
-
ptr2 = ptr2->next;
-
}
-
if(NULL == ptr2)
-
{
-
tmp = head;
-
head = head->next;
-
free(tmp);
-
return head;
-
}
-
while(ptr2->next)
-
{
-
ptr2 = ptr2->next;
-
ptr1 = ptr1->next;
-
}
-
tmp = ptr1->next;
-
ptr1->next = (ptr1->next)->next;
-
free(tmp);
-
return head;
-
}
阅读(1335) | 评论(0) | 转发(0) |