Leetcode-083

Leecode-083 Remove Duplicates from Sorted List

思路:一次遍历

题目描述

给出一个链表,如果有重复的数只记录一次

1
2
Input: 1->1->2
Output: 1->2
1
2
Input: 1->1->2->3->3
Output: 1->2->3

Solution:

  • 遍历一次 (直到为null)
    • 如果当前节点和下一个节点相同就跳过该节点
    • 如果当前节点和下一个节点不同就记录一次

Java

Solution :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode curr = head;
while (curr != null && curr.next != null){
if(curr.val == curr.next.val){
curr.next = curr.next.next;
}else{
curr = curr.next;
}
}
return head;
}
}

Python

Solution :

1
2
3
4
5
6
7
8
9
10
11
12
13
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
curr = head
while curr != None and curr.next != None:
if curr.val == curr.next.val: curr.next = curr.next.next
else: curr = curr.next
return head
打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信