題目形貌
刪除有序鏈表中的反覆節點,返轉頭節點
- 刪撤除一切反覆節點,比方1->1->2->2->3->4,返回3->4
- 反覆的節點中保存一個,比方1->1->2->2->3->4,返回1->2->3->4
刪撤除一切反覆節點
function ListNode(x){
this.val = x;
this.next = null;
}
function deleteDuplication(pHead){
if(pHead === null || pHead.next === null)
return pHead;
var H = new ListNode(null);
H.next = pHead;
var pre = H;
var cur = pHead;
while(cur !== null && cur.next !== null) {
if(cur.next.val === cur.val){
var curRepetitiveVal = cur.val;
while(cur !== null && cur.val === curRepetitiveVal) {
cur = cur.next;
}
pre.next = cur;
}else{
pre = cur;
cur = cur.next;
}
}
return H.next;
}
細節
這內里有幾個須要注重的細節:
- 新建一個空的頭節點,由於這內里牽扯到換新的鏈表頭的題目,所以為了輕易新建一個新的節點作為鏈表的頭節點
每一個反覆節點中保存一個
function ListNode(x){
this.val = x;
this.next = null;
}
function deleteDuplication(pHead){
if(pHead === null || pHead.next === null)
return pHead;
var H = new ListNode(null);
H.next = pHead;
var pre = H;
var cur = pHead;
while(cur !== null && cur.next !== null) {
if(cur.next.val === cur.val){
pre = cur;
var curRepetitiveVal = cur.val;
while(cur !== null && cur.val === curRepetitiveVal) {
cur = cur.next;
}
pre.next = cur;
}else{
pre = cur;
cur = cur.next;
}
}
return H.next;
}
細節
- 這個和刪撤除一切反覆節點的區分就是發現有雷同的節點時,pre指針立馬指向反覆的節點中的第一個節點