LeetCode_83. Remove Duplicates from Sorted List

 

83. Remove Duplicates from Sorted List

Easy

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

 

package leetcode.easy;

public class RemoveDuplicatesFromSortedList {
	@org.junit.Test
	public void test() {
		ListNode l11 = new ListNode(1);
		ListNode l12 = new ListNode(1);
		ListNode l13 = new ListNode(2);
		l11.next = l12;
		l12.next = l13;
		l13.next = null;
		print(l11);

		ListNode l21 = new ListNode(1);
		ListNode l22 = new ListNode(1);
		ListNode l23 = new ListNode(2);
		ListNode l24 = new ListNode(3);
		ListNode l25 = new ListNode(3);
		l21.next = l22;
		l22.next = l23;
		l23.next = l24;
		l24.next = l25;
		l25.next = null;
		print(l21);

		ListNode l1 = deleteDuplicates(l11);
		print(l1);
		ListNode l2 = deleteDuplicates(l21);
		print(l2);
	}

	private static void print(ListNode l) {
		while (l != null) {
			System.out.print(l.val);
			if (l.next != null) {
				System.out.print("->");
			}
			l = l.next;
		}
		System.out.println();
	}

	public ListNode deleteDuplicates(ListNode head) {
		ListNode current = head;
		while (current != null && current.next != null) {
			if (current.next.val == current.val) {
				current.next = current.next.next;
			} else {
				current = current.next;
			}
		}
		return head;
	}
}

 

转载于:https://www.cnblogs.com/denggelin/p/11592166.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值