删除链表节点
原题链接[:](https://leetcode.cn/leetbook/read/illustration-of-algorithm/7fmls1/)
代码记录:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteNode(ListNode head, int val) {
//顺序遍历链表然后进行删除,双指针法
if(head==null) return head;
if(head.val==val) return head.next;
ListNode p=head;
ListNode pre=p;
while(p!=null){
if(p.val==val){
pre.next=p.next;
break;
}
pre=p;
p=p.next;
}
return head;
}
}
//使用后递归实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteNode(ListNode head, int val) {
//后递归实现
if(head==null ){//出口
return head;
}
if(head.val==val){//出口以及当首节点和值相等时
return head.next;
}
head.next=deleteNode(head.next,val);
return head;
}
}
//使用hashmap实现,和双指针很像
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteNode(ListNode head, int val) {
//使用hashmap进行实现
if(head.val==val) return head.next;
HashMap<Integer, ListNode> map = new HashMap<Integer, ListNode>();
ListNode p=head;
ListNode pre=new ListNode(-1);
while(p!=null){
map.put(p.val,pre);
pre=p;
p=p.next;
}
if(map.get(val)!=null){
map.get(val).next=map.get(val).next.next;
}
return head;
}
}