Leetcode剑指Offer刷题指南:
解法一:双指针
/**
* 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;
//设定cur代表当前节点和pre代表上一个节点
ListNode cur = head;
ListNode pre = null;
//判断首节点是否为要删除节点,如果是,直接返回下一个节点
if (cur.val == val) return cur.next;
//不是要删除节点就向后走
while (cur.val != val) {
pre = cur;
cur = cur.next;
}
//找到了要删除节点
pre.next = pre.next.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;
ListNode cur = head;
while (cur.next != null && cur.next.val != val) {
cur = cur.next;
}
if (cur.next != null) {
cur.next = cur.next.next;
}
return head;
}
}
解法:快慢指针
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
if (head == null) return head;
ListNode slow = head;
ListNode fast = head;
//fast先走k步
while (k > 0 && fast != null) {
fast = fast.next;
k--;
}
//slow和fast一起走
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}