Another solution using stack but runtime is bad


  • 0
    R
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            Stack<ListNode> data = new Stack<ListNode>();
    		while (head != null) {
    			if (!data.isEmpty() && head.val == data.peek().val) {
    				while (head != null && data.peek().val == head.val)
    					head = head.next;
    				data.pop();
    				if (head != null) {
    					data.push(head);
    					head = head.next;
    				}
    			} else {
    				data.push(head);
    				head = head.next;
    			}
    		}
    		ListNode end = null;
    		while (!data.isEmpty()) {
    			head = data.pop();
    			head.next = end;
    			end = head;
    		}
    		return head;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.