Code & Func
2017-10-07

打卡,第14天

今天的题目是Remove Nth Node From End of List,一开始以为是道很简单的题目,后来看dicuss时才发现是自己没看清题目。

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.

一开始没看到Try to do this in one pass.,然后就用两遍遍历方法去做了:

1
int getRightN(ListNode *head,int n) {
2
ListNode *p = head;
3
int size = 0;
4
while(p != nullptr) {
5
p = p->next;
6
size++;
7
}
8
return size - n;
9
}
10
ListNode* removeNthFromEnd(ListNode* head, int n) {
11
ListNode h(0);
12
h.next = head;
13
ListNode *p = &h;
14
15
int k = getRightN(p,n);
8 collapsed lines
16
while(--k)
17
p=p->next;
18
19
head = p->next;
20
p->next = head->next;
21
delete head;
22
return h.next;
23
}

上面这个方法太简单了,还是看看在dicuss中的方法吧:

1
ListNode *removeNthFromEnd(ListNode *head, int n)
2
{
3
if (!head)
4
return nullptr;
5
6
ListNode new_head(-1);
7
new_head.next = head;
8
9
ListNode *slow = &new_head, *fast = &new_head;
10
11
for (int i = 0; i < n; i++)
12
fast = fast->next;
13
14
while (fast->next)
15
{
11 collapsed lines
16
fast = fast->next;
17
slow = slow->next;
18
}
19
20
ListNode *to_de_deleted = slow->next;
21
slow->next = slow->next->next;
22
23
delete to_be_deleted;
24
25
return new_head.next;
26
}

这个看起来会比较简单,想法就是利用快慢指针去做,先让fast指针先走n步,然后在fast指针和slow指针一起移动,这样fastslow始终保持着n个节点的距离,当fast为最后一个节点时,slow就指向倒数第n+1个节点,这时就可以把倒数第n个节点删掉了。

有一个更简洁的版本,不过有点难懂就是了:

1
ListNode* removeNthFromEnd(ListNode* head, int n)
2
{
3
ListNode** t1 = &head, *t2 = head;
4
for(int i = 1; i < n; ++i)
5
{
6
t2 = t2->next;
7
}
8
while(t2->next != NULL)
9
{
10
t1 = &((*t1)->next);
11
t2 = t2->next;
12
}
13
*t1 = (*t1)->next;
14
return head;
15
}

这个和上一个的思路其实是完全一样的,只是实现方法思路不一样就是,这里的t1是指向某个节点(包括一开始时虚拟的头结点)的next指针的指针。

上一条动态