剑指offer18.删除链表的节点
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if(head.val == val){
return head.next;
}
ListNode fast = head.next;
ListNode slow = head;
while(fast.val != val && fast!=null){
slow = fast;
fast = fast.next;
}
if(fast !=null){
slow.next = fast.next;
}
return head;
}
}
19.删除链表的倒数第N个节点
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pre = new ListNode(0);
pre.next = head;
ListNode start = pre, end = pre;
while(n != 0){
start = start.next;
n--;
}
while(start.next != null){
start = start.next;
end = end.next;
}
end.next = start;
return pre.next;
}
}
class Solution {
public ListNode removeNthFromEnd(ListNode head,int n){
ListNode pre = new ListNode(0) ;
pre.next = head;
ListNode fast = pre ,slow = pre;
while(n>0){
fast = fast.next;
if(fast == null){
return null;
}
n--;
}
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return pre.next;
}
}