LeetCode - remove-duplicates-from-sorted-list

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/toward_south/article/details/89414597

题目:

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.

题意:

有序链表,删除重复元素

解题思路:

比较当前结点的value 和当前结点的下一个value值是否相等,是的话就删除

这里需要注意判空,不然会抛出空指针异常,还有应该注意比较的时候应该用while,用if的话 如果是1,1,1就只会删除1个1罢了。

扫描二维码关注公众号,回复: 6108673 查看本文章

Java代码:

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

猜你喜欢

转载自blog.csdn.net/toward_south/article/details/89414597