- 一、题目描述
- 二、示例
- 三、难度
- 四、代码
- Java版
四、代码 Java版简单
/**
* @author Kidd
* @create 2022-05-08 10:08
*/
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) return null;
// 快指针fast用来探路
ListNode slow = head, fast = head.next;
while (fast != null) {
if (slow.val != fast.val) {
slow.next = fast;
slow = slow.next;
}
fast = fast.next;
}
// 断开与后面重复元素的连接
slow.next = null;
return head;
}
public static void main(String[] args) {
ListNode node4 = new ListNode(3);
ListNode node3 = new ListNode(3,node4);
ListNode node2 = new ListNode(2,node3);
ListNode node1 = new ListNode(1,node2);
ListNode head = new ListNode(1,node1);
ListNode list = new Solution().deleteDuplicates(head);
while (list != null) {
System.out.print(list.val+" ");
list = list.next;
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)