删除当前节点 :将当前节点的下一节点值附给当前节点,然后删除当前节点的下一节点,这样就等效为删除当前接节点了。
查找倒数第K个节点:前后节点
public static Node lastk(Node head,int k){
if(head==null)
return null;
Node fnode = head;
Node bnode = head;
for(int i=0;i<k-1&&fnode!=null;i++){
fnode=fnode.next;
}
if(fnode==null)
return null;
while(fnode.next!=null){
fnode = fnode.next;
bnode = bnode.next;
}
return bnode;
}
使用hash法。
步骤:
(1)建立一个hash表,key为链表中已经遍历的节点内容,初始时为空。
(2)从头开始遍历单链表中的节点。
看next是否已经存在,存在则跳过next,不存在则把next加入map,继续遍历
public static Node deleteNode(Node head){
HashMap map = new HashMap();
if(pHead == null ||pHead.next==null){
return pHead;
}
ListNode current = pHead;
ListNode next = pHead.next;
while(next!=null&¤t!=null){
if(map.get(next.val)==null){
map.put(next.val, 1);
current = next;
next = current.next;
}else{
current.next = next.next;
next.next=null;
next = current.next;
}
}
return pHead;
}
return head;
}