ListNode 头结点的理解:
一个链表头节点为head
head -> 1 -> 2 -> 3 -> 4 -> 5 -> 6
head叫做链表的头节点
1 所在的节点叫做链表的首节点(不知叫法是否准确)
从定义上严格来说, 头节点head本身并没有值,它只是一个指向首节点1的指针。也就是说head.val为空,head.next.val=1。即head的下一个节点才是1的节点。那上述的链表就有7个节点(包含头节点head)。
但是,在一些编程题里,有可能把头节点默认为首节点。也就是说head不仅指向1,而且head.val=1,那head.next.val=2。即head就是1的节点,head的下一个节点是2的节点。那么这个链表一个就有6个节点(head和1所在的节点看作一个节点)。
1(head) -> 2 -> 3 -> 4 -> 5 -> 6
因此,若定义一个Listnode cur = head;则cur.val = 1
但有时我们需要定义一个辅助节点
ListNode now = new ListNode(-1);
now.next = head;
这表示定义一个节点now,它没有值,它指向头节点head。
例题:在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5处理后为 1->2->5
(此题默认头结点就是首节点,且需要定义辅助节点来解决)
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if(pHead == null )
return pHead;
ListNode now = new ListNode(-1);
now.next = pHead;
ListNode pre = now;
ListNode cur = pHead;
ListNode n = pHead.next;
while( cur!=null && n!=null){
if(cur.val==n.val){
while(n!=null && n.val == cur.val)
n = n.next;
pre.next=n;
cur=pre.next;
if(n != null)
n = n.next;
}
else{
pre=cur;
cur=n;
n=n.next;
}
}
return now.next;
}
}