首页 > 其他分享 >[刷题记录Day4]Leetcode链表专题

[刷题记录Day4]Leetcode链表专题

时间:2023-07-19 21:12:38浏览次数:44  
标签:count ListNode cur Day4 fast next 链表 null Leetcode

No.1

题目

两两交换链表中的节点

思路

  • 模拟类型题目
  • 两个节点前后交换,同时记住原来的下一个节点
  • 虚拟头节点

代码

public ListNode swapPairs(ListNode head) {
	ListNode dummyHead = new ListNode(-1, head);
	ListNode cur = dummyHead;
	while (cur.next != null && cur.next.next != null) {
		ListNode firstNode = cur.next;
		ListNode secondNode = firstNode.next;
		ListNode temp = secondNode.next;
		// swap
		cur.next = secondNode;
		secondNode.next = firstNode;
		firstNode.next = temp;
		// next round
		cur = firstNode;
	}
	return dummyHead.next;
}

No.2

题目

删除链表的倒数第 N 个结点

思路

  • 快慢指针,让快指针领先N个节点走,随后保持快慢指针的差距为N,等快指针指向null,慢指针即指向倒数第N个节点
  • 实际处理中,拿到慢指针的上一个节点比较好做删除操作,所以让快指针领先N+1步比较方便
  • 虚拟头节点

代码

public ListNode removeNthFromEnd(ListNode head, int n) {  
    ListNode dummyHead = new ListNode(-1, head);  
    ListNode slow = dummyHead, fast = dummyHead;  
    for (int i = 0; i < n + 1; i++) {  
        fast = fast.next;  
    }  
    while (fast != null) {  
        slow = slow.next;  
        fast = fast.next;  
    }  
    // 结束while循环的时候,就是找到了被删除节点的上一个节点  
    slow.next = slow.next.next;  
    return dummyHead.next;  
}

No.3

题目

面试题 02.07. 链表相交

思路

  • 分别计算长度
  • 从后续长度相等地方开始找

代码

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {  
    int A_count = 0, B_count = 0;  
    ListNode A_cur = headA, B_cur = headB;  
    while (A_cur != null) {  
        A_cur = A_cur.next;  
        A_count++;  
    }  
    while (B_cur != null) {  
        B_cur = B_cur.next;  
        B_count++;  
    }  
    A_cur = headA;  
    B_cur = headB;  
    // 让A指向最长的链表  
    if (A_count < B_count) {  
        int temp_count = A_count;  
        A_count = B_count;  
        B_count = temp_count;  
        ListNode temp_node = A_cur;  
        A_cur = B_cur;  
        B_cur = temp_node;  
    }  
    for (int i = 0; i < (A_count - B_count); i++) {  
        A_cur = A_cur.next;  
    }  
    while (A_cur != null && B_cur != null) {  
        if (A_cur == B_cur)  
            return A_cur;  
        A_cur = A_cur.next;  
        B_cur = B_cur.next;  
    }  
    return null;  
}

No.4

题目

环形链表 II

思路

  • 快慢双指针
  • while循环:有环则寻找入口,无环则结束循环,返回null

代码

public ListNode detectCycle(ListNode head) {  
    ListNode slow = head, fast = head; // 初始化 speed(fast) = 2 * speed(slow)  
    while (fast != null && fast.next != null) { // fast步长为2,保证不会访问空指针  
        slow = slow.next;  
        fast = fast.next.next;  
        if (slow == fast) { // 有环,找到相遇点  
            ListNode p1 = slow;  
            ListNode p2 = head;  
            // 推论:2个节点,一个从开头出发,一个从meet出发,以相同速度前进,再相遇就是环入口  
            while (p1 != p2) {  
                p1 = p1.next;  
                p2 = p2.next;  
            }  
            return p1;  
        }  
    }  
    return null; // 有null指针,无环  
}

标签:count,ListNode,cur,Day4,fast,next,链表,null,Leetcode
From: https://www.cnblogs.com/tomatoQt/p/17566751.html

相关文章

  • Python基础day48
    伪类选择器<style>/*未访问时候显示的*/a:link{color:#FF0000;}/*鼠标移动到链接上*/a:hover{color:#FF00FF}/*选定的链接鼠标点击时出现*/a:active{c......
  • LeetCode 875. Koko Eating Bananas 二分答案
    Kokolovestoeatbananas.Thereare\(n\)pilesofbananas,the\(i\)thpilehas\(piles[i]\)bananas.Theguardshavegoneandwillcomebackinhhours.Kokocandecideherbananas-per-houreatingspeedofk.Eachhour,shechoosessomepileofb......
  • LeetCode 1011. Capacity To Ship Packages Within D Days 二分答案
    Aconveyorbelthaspackagesthatmustbeshippedfromoneporttoanotherwithindaysdays.Theithpackageontheconveyorbelthasaweightof\(weights[i]\).Eachday,weloadtheshipwithpackagesontheconveyorbelt(intheordergivenby\(wei......
  • 2 链表
    #链表##1链表基础理论什么是链表,链表是一种通过指针串联在一起的线性结构,每一个节点由两部分组成,一个是数据域一个是指针域(存放指向下一个节点的指针),最后一个节点的指针域指向null(空指针的意思)。链表的入口节点称为链表的头结点也就是head。-单链表![img](https://img......
  • leetcode练习
    分类题单:code难度:简单中等困难类型:数组链表字符串二叉树排序解法:递归和迭代滑动窗口 MapStack堆双指针​ 前缀和动态规划解答:解答code[1.两数之和](#1.两数之和)[2.两数相加](#2.两数相加)[3.无重复字符的最长子串](#3.无重复字符的最长子串)[5.......
  • leetcode 546. 移除盒子
    1.题目读题 链接:https://www.nowcoder.com/questionTerminal/a5390d76441647fbb182f34bee6a1ca7来源:牛客网一维消消乐小v在vivo手机的应用商店中下载了一款名为“一维消消乐”的游戏,介绍如下:1、给出一些不同颜色的豆子,豆子的颜色用数字(0-9)表示,即不同的数字表示不同的......
  • [LeetCode] 2461. Maximum Sum of Distinct Subarrays With Length K
    Youaregivenanintegerarray nums andaninteger k.Findthemaximumsubarraysumofallthesubarraysof nums thatmeetthefollowingconditions:Thelengthofthesubarrayis k,andAlltheelementsofthesubarrayare distinct.Return themaxim......
  • [LeetCode] 2222. Number of Ways to Select Buildings
    Youaregivena 0-indexed binarystring s whichrepresentsthetypesofbuildingsalongastreetwhere:s[i]='0' denotesthatthe ith buildingisanofficeands[i]='1' denotesthatthe ith buildingisarestaurant.Asacityoff......
  • Leetcode日记
    日期题号题目解法难度2023-07-112741给定一个互不相同的正整数数组,找出特别排列(相邻元素互模任一为0)的总数目。取余dp+记忆,位运算,取余注意先加后取⭐⭐⭐1911求数组最大子序列交替和(偶数下标元素和减奇数下标元素和)dp⭐2023-07-121857有向图中求路径......
  • LeetCode 35.搜索插入位置
    题目:给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。请必须使用时间复杂度为 O(logn) 的算法。示例1:输入:nums=[1,3,5,6],target=5输出:2示例 2:输入:nums=[1,3,5,6],target=2输出:1......