LeetCode Remove Duplicates from Sorted List & Remove Duplicates from Sorted List II

Remove Duplicates from Sorted List

 

Description:

Given a sorted linked list, delete all duplicates such that each element appear only once.

Solution:

每次while循环,都判断当前节点与下一个节点的val是否一样,一样则改变当前节点的next指针,否则跳到下一个节点。

import java.util.*;

public class Solution {
	public ListNode deleteDuplicates(ListNode head) {
		ListNode temp = head;
		ListNode next;
		while (temp != null) {
			next = temp.next;
			if (next == null)
				break;
			if (temp.val == next.val) {
				temp.next = next.next;
			} else {
				temp = next;
			}
		}
		return head;
	}
}

Remove Duplicates from Sorted List II

  Description:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Solution:

利用two pointer方法,每次对于当下要遍历的节点t1,都用进行另外一次遍历,记为t2,一直搜索到null或者t1和t2的val不同。如果t2是t1的next,那么就表示t1没有重复值,否则t1赋值到t2,继续遍历。

import java.util.*;

public class Solution {
	public ListNode deleteDuplicates(ListNode head) {
		ListNode t1, t2;

		t1 = head;
		t2 = head;
		while (t1 != null) {
			t2 = t1;
			while (t2 != null) {
				if (t2.val != t1.val)
					break;
				t2 = t2.next;
			}
			if (t1.next == t2) {
				break;
			} else {
				t1 = t2;
			}
		}

		head = t1;
		t1 = t2 = head;
		ListNode temp = head;
		while (t1 != null) {
			t2 = t1;
			while (t2 != null) {
				if (t2.val != t1.val)
					break;
				t2 = t2.next;
			}
			if (t1.next == t2) {
				temp.next = t1;
				temp = temp.next;
				System.out.println(temp.val);
				t1.next = null;
				t1 = t2;
			} else {
				t1 = t2;
			}
		}

		return head;
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值