Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
输入排序过的链表,删除相同的元素。
挺简单的题目,头脑有点乱,搞的了做了半小时才做出来。。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null) //空结点或者单节点直接返回
return head;
ListNode t = head;
while(true){
if(t==null||t.next==null) //到链表尾或者下一个是链表尾
break;
while(t.next!=null&&t.next.val==t.val) //迭代排除相同的,注意考虑到了链表尾
t.next=t.next.next;
t= t.next;
}
return head;
}
}
本文介绍了一种从已排序链表中移除所有重复元素的方法,确保每个元素只出现一次。通过迭代检查相邻元素并跳过重复项来实现这一目标。
715

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



