问题链接
83. 删除排序链表中的重复元素
问题描述
给定一个已排序的链表的头 head
, 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
示例

解题思路
因为链表已经排序过了,遍历一次,删除相邻重复元素即可。
代码示例(JAVA)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode node = head;
while (node.next != null) {
ListNode next = node.next;
if (node.val == next.val) {
node.next = next.next;
} else {
node = next;
}
}
return head;
}
}
执行结果

网友评论