链表

难度简单

题目描述

image.png

解题思路

  • 指定 cur 指针指向头部 head
  • 当 cur 和 cur.next 的存在为循环结束条件,当二者有一个不存在时说明链表没有去重复的必要了
  • 当 cur.val 和 cur.next.val 相等时说明需要去重,则将 cur 的下一个指针指向下一个的下一个,这样就能达到去重复的效果
  • 如果不相等则 cur 移动到下一个位置继续循环
  • 时间复杂度:O(n)O(n)

作者:guanpengchn
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/solution/hua-jie-suan-fa-83-shan-chu-pai-xu-lian-biao-zhong/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Code

  1. class ListNode {
  2. int val;
  3. ListNode next;
  4. ListNode() {
  5. }
  6. ListNode(int val) {
  7. this.val = val;
  8. }
  9. ListNode(int val, ListNode next) {
  10. this.val = val;
  11. this.next = next;
  12. }
  13. }
  14. public ListNode deleteDuplicates(ListNode head) {
  15. ListNode cur = head;
  16. while (cur != null && cur.next != null) {
  17. if (cur.val == cur.next.val) {
  18. cur.next = cur.next.next;
  19. } else {
  20. cur = cur.next;
  21. }
  22. }
  23. return head;
  24. }