算法设计与分析(13)
题目:Remove Nth Node From End of List
问题描述:
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.
算法思路:
这是个非常容易的问题,主要是考虑如何一次遍历完成任务。
首先我们想到一个在面试中很常见的问题:给定你一个指针*p, 该指针指向一个单链表的某个节点,如何使用该指针删除当前的节点。只要解决这个问题,当然我们就可以通过一次遍历的方法解决问题。该问题的解决方法是:把当前节点用下一个节点来重新赋值,然后删除下一个节点。
但是,在我们的问题中,还要考虑一些特殊情况。
(1)当链表只有一个节点,那么我们直接删除当前节点,返回NULL指针。
if (head->next == NULL)
{
delete head;
head == NULL;
return head;
}
(2)当需要删除的节点是当前链表的最后一个节点(即n==1),我们是指针*first
指向链表最后一个节点,指针*second
指向*first
的上一个节点,然后删除*first
的节点,使*second->next = NULL
。
if (n == 1)
{
first = head->next;
second = head;
while (first->next != NULL)
{
first = first->next;
second = second->next;
}
delete first;
second->next = NULL;
}
(3)当需要删除的节点不是当前链表的最后一个节点(即n!=1),是指针指针*first
指向链表最后一个节点,*second
指向需要删除的节点。然后使用删除链表中间节点的方法,删除*second
指向的节点。
else
{
first = head;
for (int i = 1; i < n; ++i)
first = first->next;
second = head;
while (first->next != NULL)
{
first = first->next;
second = second->next;
}
ListNode* del = second->next;
second->val = del->val;
second->next = del->next;
delete del;
}
代码实现:
#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 *first, *second;
if (head->next == NULL)
{
delete head;
head == NULL;
return head;
}
if (n == 1)
{
first = head->next;
second = head;
while (first->next != NULL)
{
first = first->next;
second = second->next;
}
delete first;
second->next = NULL;
}
else
{
first = head;
for (int i = 1; i < n; ++i)
first = first->next;
second = head;
while (first->next != NULL)
{
first = first->next;
second = second->next;
}
ListNode* del = second->next;
second->val = del->val;
second->next = del->next;
delete del;
}
return head;
}