题目描述:
删除有序链表中的重复节点,返回头节点,例如1->1->2->2->3->4,返回3->4
public class Offer18 {
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node31 = new ListNode(3);
ListNode node4 = new ListNode(4);
node1.next = node2;
node2.next = node3;
node3.next = node31;
node31.next=node4;
deleteDuplication(node1);
System.out.println(node1);
}
//循环写法
public static ListNode deleteDuplication(ListNode pHead) {
//设置一个新头结点,用于删除原头结点(如果需要的话)
ListNode first = new ListNode(-1);
//插入到原头结点前,成为头结点
first.next = pHead;
//设置一指针,指向当前节点
ListNode current = pHead;
//前指针,指向前一节点
ListNode pre = first;
while (current != null && current.next != null) {
if (current.val == current.next.val) {
//记录重复值
int val1 = current.val;
while (current != null && current.val == val1) {
//删除当前节点
current = current.next;
//当前节点为上一节点的下一节点,使current重新指向当前节点
pre.next = current;
}
} else {
// 不重复则current和pre向后移动
pre = current;
//这里是移动不是删除,因为之前的current已经是pre节点了
current = current.next;
}
}
return first.next;
}
}
class ListNode {
//属性定义成公开的方便调用和使用
public int val;
//公有属性
public ListNode next;
ListNode(int val) {
this.val = val;
}
}