Remove Duplicates from Sorted List (E)
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
题意
对于有序链表中含有重复值的结点,只保留其中一个。
思路
遍历就完事了。
代码实现
/**
* 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 cur = head;
while (cur != null) {
ListNode temp = cur.next;
// 找到第一个与cur结点值不同的结点
while (temp != null && temp.val == cur.val) {
temp = temp.next;
}
cur.next = temp;
cur = temp;
}
return head;
}
}
本文介绍了一种从已排序链表中移除重复元素的算法,确保每个元素仅出现一次。通过遍历链表并调整指针,有效地实现了这一目标。提供了详细的代码实现,包括注释解释。
724

被折叠的 条评论
为什么被折叠?



