1、遍历链表,利用栈中存放结点
2、比较当前结点和栈中的末尾元素: 相等则继续遍历后续的结点直到遍历到 不等的结点node 或者null
3、弹栈并判断,栈的大小是否=0(前方还是否有节点/栈中的末尾元素):等于0则,重置pHead;不等于0则将栈中的末尾元素指向不等的结点node
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode deleteDuplication(ListNode pHead) {
if(pHead==null){
return pHead;
}
Stack<ListNode> stack = new Stack();
stack.push(pHead);
ListNode cur = pHead.next;
while(cur!=null){
if(stack.lastElement().val==cur.val){
//寻找后续重复元素
while(cur!=null&&stack.lastElement().val==cur.val){
cur = cur.next;//删除全部重复元素
}
stack.pop();//弹出重复元素
if(stack.size()!=0){//重复元素前还存在结点
stack.lastElement().next = cur;
}else{//重复元素前不存在结点
pHead = cur;
}
}
stack.push(cur);
if(cur!=null)
cur = cur.next;
}
return pHead;
}
}
京公网安备 11010502036488号