Remove Duplicates from Sorted List II (M)
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 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 ans = null, last = null;
while (head != null) {
ListNode temp = head.next;
int count = 0;
// 判断head的值是否重复,并找到下一个值不同的结点
while (temp != null && temp.val == head.val) {
temp = temp.next;
count++;
}
if (count == 0) {
head.next = null; // 将该结点单独取出,断开与之后结点的联系
if (ans == null) {
ans = head;
last = head;
} else {
last.next = head;
last = last.next;
}
}
head = temp;
}
return ans;
}
}
本文介绍了一种算法,用于从已排序的链表中移除所有重复出现的元素,仅保留原始链表中的唯一数值。通过遍历链表并检查每个节点的值,将不重复的节点提取出来并构建新的链表。
724

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



