链表类题目

链表类题目虽然难度不会特别大,但是有的题目还是很具有技巧性,而且在刷题过程中,我经常对循环体的条件感到纠结,用这篇文章记录一下:

1. 链表反转类

206. 反转链表 - 力扣(LeetCode)

这道题比较经典,采用双指针即可解决,可以作为一个模板记下来:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    //双指针反转链表
    //直接把cur指向pre,然后更新cur,pre直至cur == null即可
    public ListNode reverseList(ListNode head) {
        ListNode pre = null, cur = head;
        while(cur != null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

 

链表内指定区间反转_牛客题霸_牛客网 (nowcoder.com)

这道题是面试快手时的原题,大概思路和反转链表差不多,但是由于加入了区间,所以需要记录区间外的左右节点并在区间内反转完成后进行重新连接:

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param m int整型 
     * @param n int整型 
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        // 什么时候使用dummy呢?使用dummy一定就能避开分类讨论吗?
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy, cur = head;
        // left和right表示区间外左右节点
        ListNode left, right;
        // 找到区间外左节点
        for(int i = 1; i < m; i++){
            pre = pre.next;
        }
        left = pre;
        pre = pre.next;
        cur = pre.next;
        // 反转区间内节点(和反转链表一样采用一个哨兵指针)
        for(int i = m; i < n; i++){
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        // 区间外右节点恰好就是此时的cur
        right = cur;
        // 更新区间外节点的连接
        left.next.next = right;
        left.next = pre;
        return dummy.next;
    }
}

面试的时候比较紧张,没完全写出来,难受唉。

待续。。。

posted @ 2023-06-07 11:21  Vege_dog  阅读(17)  评论(0)    收藏  举报