题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。
例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
思路
(1)若链表为空或者只有一个结点,直接返回head
(2)在链表不空的情况下,定义一个新链表用于存放去重后的结点,若head.next也不为空且head.val == head.next.val就向后移,直至相邻结点的值不相等;将不重复的值放到定义的新链表中即可
代码
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode deleteDuplication(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode newHead = new ListNode(0);
ListNode tail = newHead;
while(head!=null){
if(head.next != null && head.val == head.next.val){
while(head.next != null && head.val == head.next.val){
head = head.next;
}
head = head.next;
}else{
tail.next = new ListNode(head.val);
head = head.next;
tail = tail.next;
}
}
return newHead.next;
}
}