题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-II
http://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
三指针,如果一个值与前后都不相等说明这个节点就是不重复的,删除其他节点即可。
首先new一个新的头节点,
遍历链表,如果当前节点与前后节点均不同,则将这个节点加入到新链表中,这里如果pre=null则说明是第一个节点,就不用判断与pre是否相等了,next=null则说明是最后一个节点同理。否则跳过重复的节点。
返回新头节点的下一个即为答案。
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
// write code here
if (head == null || head.next == null) {
return head;
}
ListNode newHead = new ListNode(0);
ListNode pHead = newHead;
ListNode cur = head, next = head.next, pre = null;
while (cur != null) {
if ((pre == null || pre.val != cur.val)
&& (next == null || next.val != cur.val)) {
pHead.next = cur;
pHead = pHead.next;
}
pre = cur;
cur = next;
if (next != null) {
next = next.next;
}
}
pHead.next = null;
return newHead.next;
}
}