题目: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个结点就是设置一个指针,先走n步,然后另一个指针开始遍历链表。当第一个指针走到链表尾部时,第二个指针正好指向倒数第n个结点。接着执行链表结点删除就ok了,注意判断空链表和只有一个结点的链表。
C++代码如下:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (head == NULL)
return NULL;
int k = 1;
ListNode *p = head, *q = head, *qPre = NULL;
while (k < n)
{
p = p->next;
k++;
}
while (p->next != NULL)
{
qPre = q;
q = q->next;
p = p->next;
}
if (qPre == NULL)
{
head = q->next;
delete q;
}
else
{
qPre->next = q->next;
q = NULL;
delete q;
}
return head;
}