【remove-duplicates-from-sorted-list】
【题目描述】
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.
【分析】
这是一道比较简单的链表操作的题目,要求是删去有序链表中重复的元素。方法比较清晰,维护两个指针,一个指向当前不重复的最后一个元素,一个进行依次扫描,遇到不重复的则更新第一个指针,继续扫描,否则就把前面指针指向当前元素的下一个(即把当前元素从链表中删除)。时间上只需要一次扫描,所以是O(n),空间上两个额外指针,是O(1)。
【代码】
package leetcode.easy.easy;
public class DeleteDuplicates {
public class ListNode {
int val;
ListNode next;
public ListNode(int x) {
val = x;
next = null;
}
}
public static void main(String[] args) {
}
//方法1
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return null;
}
ListNode prev = head;
ListNode cur = head.next;
while (cur != null) {
if (prev.val == cur.val) {
prev.next = cur.next;
cur = cur.next;
} else {
prev = cur;
cur = cur.next;
}
}
return head;
}
//方法2
public ListNode deleteDuplicates2(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode cur = head;
while(cur!=null&&cur.next!=null){
if(cur.val==cur.next.val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return head;
}
}
【remove-duplicates-from-sorted-list ii】
【题目】
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given1->2->3->3->4->4->5, return1->2->5.
Given1->1->1->2->3, return2->3.
【代码】
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode t = new ListNode(0);
t.next = head;
ListNode p = t;
while(p.next!=null&&p.next.next!=null){
if(p.next.val == p.next.next.val){
int dup = p.next.val;
while(p.next!=null&&p.next.val==dup){
p.next = p.next.next;
}
}else{
p=p.next;
}
}
return t.next;
}
}