Dummy node 是链表问题中一个重要的技巧,中文翻译叫“哑节点”或者“假人头结点”。
Dummy node 是一个虚拟节点,也可以认为是标杆节点。Dummy node 就是在链表表头 head 前加一个节
点指向 head,即 dummy -> head。Dummy node 的使用多针对单链表没有前向指针的问题,保证链表的
head 不会在删除操作中丢失。除此之外,还有一种用法比较少见,就是使用 dummy node 来进行head的
删除操作,比如 Remove Duplicates From Sorted List II,一般的方法current = current.next 是无法删除
head 元素的,所以这个时候如果有一个dummy node在head的前面。
所以,当链表的 head 有可能变化(被修改或者被删除)时,使用 dummy node 可以很好的简化代码,最
Dummy node 是一个虚拟节点,也可以认为是标杆节点。Dummy node 就是在链表表头 head 前加一个节
点指向 head,即 dummy -> head。Dummy node 的使用多针对单链表没有前向指针的问题,保证链表的
head 不会在删除操作中丢失。除此之外,还有一种用法比较少见,就是使用 dummy node 来进行head的
删除操作,比如 Remove Duplicates From Sorted List II,一般的方法current = current.next 是无法删除
head 元素的,所以这个时候如果有一个dummy node在head的前面。
所以,当链表的 head 有可能变化(被修改或者被删除)时,使用 dummy node 可以很好的简化代码,最
终返回 dummy.next 即新的链表。(http://algorithm.yuanbin.me)
主要可以用这个节点来处理头结点可能变动的情况。
Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL) return NULL;
ListNode *temphead = new ListNode(0);
temphead->next = head;//新开辟一个指针指向头结点,因为头结点也可能需要删除,返回是返回temphead->next即可
ListNode*pre = temphead;//用于保存前一个指针
while (head&&head->next)
{
if(head->val==head->next->val)
{
while (head->next&&head->val == head->next->val)
{
head->next = head->next->next;
}
pre->next = head->next;
head = head->next;
}
else
{
pre = head;//不需删除则保存下前一个节点
head = head->next;//继续向后执行
}
}
return temphead->next;
}
};
Reverse Linked List II
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (head == NULL||n<m) return NULL;
ListNode *dummy = new ListNode(0);//同样可能头结点改变需要dummy节点
ListNode *pre = dummy;
dummy->next = head;
int count = 0;
while (head)
{
count++;
if (count==m)
{
ListNode *temppre =NULL;
ListNode *next=NULL;
while (count!=n+1)//翻转
{
count++;
next = head->next;
head->next = temppre;
temppre = head;
head = next;
}
pre->next->next = next;//当前next及为翻转后指向的那个
pre->next = temppre;//把需要翻转的前一个节点指向翻转后的节点
}
else
{
pre = head;
head = head->next;
}
}
return dummy->next;
}
};