==========================努力奋斗财源广进==========================
给出一个升序排序的链表,删除链表中的所有重复出现的元素,只保留原链表中只出现一次的元素。
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) return head;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode cur = dummy;
while(cur.next != null && cur.next.next != null){
if(cur.next.val == cur.next.next.val){
int tem = cur.next.val;
while(cur.next != null && cur.next.val == tem){
cur.next = cur.next.next;
}
}else{
cur = cur.next;
}
}
return dummy.next;
}
}
//待定
只是使用了一个指针,但是新增了一个头节点起了很大的作用。在if条件里面新建临时变量保存当前重复的值,如果重复就覆盖前一个节点。直到出现新值
评论区记录复习记录
评论