题解 | #删除有序链表中重复的元素-I#
删除有序链表中重复的元素-I
https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
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 ListNode cur = head; //遍历链表 while(cur!=null&&cur.next!=null){ ListNode next = cur.next; //将所有重复的元素删除 while(cur.val==next.val&&next!=null&&next.next!=null){ //这里可能会溢出,所以上述条件加上next.next!=null cur.next = next.next; next = cur.next; } //将有可能漏掉的元素删除 if(cur.next!=null){ if(cur.val==cur.next.val){ cur.next = null; } } //指针往后移 cur = cur.next; } return head; } }
#数据结构编程链表#