题解 | #删除有序链表中重复的元素-I#
删除有序链表中重复的元素-I
https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
// 由于链表从小到大排序,则采用双指针算法,一个放在数字点,另一个一直走直到与slow指针数值不同
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 slow = head;
ListNode fast = head;
// 开始判断(以fast为null为结束条件)
while(fast != null){
// 判断是否相同,相同则前进,直到不相同为止
while(fast.val == slow.val){
fast = fast.next;
// 如果fast到头,则无val值,需要停止,否则报错
if(fast == null){
break;
}
}
// 赋值
slow.next = fast;
slow = slow.next;
}
return head;
}
}

