Remove Duplicates from Sorted List

原题: https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/
题意: 给定一个排序的链表,删除所有重复项,使每个元素只显示一次。
例子: 
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
标签: duplicates、sorted、remove、list、链表、面试
猜你感兴趣的圈子:
LeetCode交流圈
  • Bingo
    2017-08-11 12:43:20 1楼#1层
    Java解法一:
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if(head == null || head.next == null)return head;
            head.next = deleteDuplicates(head.next);
            return head.val == head.next.val ? head.next : head;
        }
    }
  • Bingo
    2017-08-11 12:43:47 2楼#1层
    Java解法二:
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            ListNode list = head;
             
             while(list != null) {
            	 if (list.next == null) {
            		 break;
            	 }
            	 if (list.val == list.next.val) {
            		 list.next = list.next.next;
            	 } else {
            		 list = list.next;
            	 }
             }
             
             return head;
        }
    }
  • 回复
隐藏