题解 | #删除链表中重复的结点#
删除链表中重复的结点
http://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef
*/
public class Solution {
public ListNode deleteDuplication(ListNode pHead) {
//如果链表头节点为空 或 只有一个节点 特判
if(pHead == null) return null;
if(pHead.next == null) return pHead;
//虚拟头节点
ListNode dum = new ListNode(-1);
ListNode cur = dum;
ListNode t = pHead;
while(t != null){
//判断如果有重复的节点,直接跳两步
while(t!= null && t.next != null && t.val == t.next.val) t = t.next.next;
if(t == null) break;
//记录一下当前节点的下一个节点
ListNode next = t.next;
cur = cur.next = t;
//注意连上节点后将下一个节点置为null
t.next = null;
//跳到下一个节点
t = next;
}
//当最后的节点值跟第头节点的val相等 或者全都是重复节点 直接返回null
if(cur.val == pHead.val || dum.next == null) return null;
return dum.next;
}
} 