删除链表的节点

题目描述

image

思路

基本操作

代码实现

/**
 * 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) {
        ListNode pre=null,cur=head;
        while(cur!=null){
            if(cur.val!=val){
                pre=cur;
                cur=cur.next;
            }else{
                if(pre==null){
                    head=cur.next;
                }else{
                    pre.next=cur.next;
                }
                break;
            }
        }
        return head;
    }
}

复杂度分析

时间复杂度

O(N)

空间复杂度

O(1)

反思不足

思路

对删除节点是第一个节点的处理不熟练

题目描述

image

思路

双指针

双指针,让前一个指针与后一个指针始终保持我们需要的距离,让后一个指针寻找最后一个元素

对于这类需要备份一个节点的题,双指针尤其好用,找到两个指针间的联系即可

代码实现

/**
 * 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 left=head,right=head;
        int cth=1;
        while(cth<k){
            right=right.next;
            cth++;
        }
        while(right.next!=null){
            right=right.next;
            left=left.next;
        }
        return left;
    }
}

复杂度分析

时间复杂度

O(N)

空间复杂度

O(1)

反思不足

思路

一点就通,这次还算OK