import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 * @return ListNode类 */ public ListNode deleteDuplicates (ListNode head) { // write code here if (head == null || head.next == null) { return head; } Stack<ListNode> stack = new Stack<>(); ListNode cur = head; while (cur != null) { if (stack.isEmpty() || stack.peek().val != cur.val) { stack.push(cur); } cur = cur.next; } ListNode newHead = stack.pop(); newHead.next = null; while (!stack.isEmpty()) { cur = stack.pop(); cur.next = newHead; newHead = cur; } return newHead; } }