题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-II
http://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
直接使用栈进行去重
Stack<Integer> stack = new Stack<>();
ListNode root = new ListNode(-1);
ListNode cur = head, p;
stack.push(root.val);
while (cur != null){
if (cur.val != stack.peek()){
p = cur;
stack.push(p.val);
cur = cur.next;
}else {
int s = stack.pop();
while (cur != null && cur.val == s){
cur = cur.next;
}
}
}
root = null;
while (!stack.isEmpty()){
int s = stack.pop();
ListNode node = new ListNode(s);
node.next = null;
if (root == null){
root = node;
}else {
node.next = root;
root = node;
}
}
return root.next;
腾讯公司福利 1143人发布