单链表

删除当前节点 :将当前节点的下一节点值附给当前节点,然后删除当前节点的下一节点,这样就等效为删除当前接节点了。

单链表反转

 

查找倒数第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&&current!=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;
}

posted on 2017-08-19 00:04  zhangxiaoyu  阅读(138)  评论(0)    收藏  举报

导航