题目:在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表 1->2->3->3->4->4->5 处理后为 1->2->5
数据范围:链表长度满足 0≤n≤1000 ,链表中的值满足 1≤val≤1000
进阶:空间复杂度 O(n)\O(n) ,时间复杂度 O(n) \O(n)
例如输入{1,2,3,3,4,4,5}时,对应的输出为{1,2,5},对应的输入输出链表如下图所示:
示例1
输入:{1,2,3,3,4,4,5}
返回值:{1,2,5}
示例2
输入:{1,1,1,8}
返回值:{8}
我的解法(使用栈):
import java.util.*;
public class Solution {
public ListNode deleteDuplication(ListNode pHead) {
Stack<ListNode> stack = new Stack<>();
if(pHead == null){
return null;
}
while(pHead != null) {
if(stack.empty()){
stack.push(pHead);
pHead = pHead.next;
} else {
if(pHead.val != stack.peek().val) {
stack.push(pHead);
pHead = pHead.next;
} else {
pHead = pHead.next;
if(pHead == null) {
stack.pop();
} else {
if(pHead.val != stack.peek().val) {
stack.pop();
stack.push(pHead);
pHead = pHead.next;
}
}
}
}
}
ListNode newNode = null;
while(!stack.empty()) {
ListNode popNode = stack.peek();
stack.pop();
popNode.next = newNode;
newNode = popNode;
}
return newNode;
}
}
高赞解法(双指针)