Given a linked list, determine if it has a cycle in it. To represent a cycle in the given linked list, we use an integer poswhich represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in t…
题意:判断链表是否有环. 分析:快慢指针. /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCycle(ListNode *head) { ListNode* fast = head; ListNode…
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次.找出那个只出现了一次的元素. 说明: 你的算法应该具有线性时间复杂度. 你可以不使用额外空间来实现吗? 示例 1: 输入: [2,2,1] 输出: 1 示例 2: 输入: [4,1,2,1,2] 输出: 4 知识点: 交换律:a ^ b ^ c <=> a ^ c ^ b 任何数于0异或为任何数 0 ^ n => n 相同的数异或为0: n ^ n => 0…
题目意思:链表有环,返回true,否则返回false 思路:两个指针,一快一慢,能相遇则有环,为空了没环 ps:很多链表的题目:都可以采用这种思路 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCyc…
Given a linked list, determine if it has a cycle in it. Follow up:Can you solve it without using extra space? 题意: 给定一个链表,判断是否有环 思路: 快慢指针 若有环,则快慢指针一定会在某个节点相遇(此处省略证明) 代码: public class Solution { public boolean hasCycle(ListNode head) { ListNode fast =…
141. Linked List Cycle Given a linked list, determine if it has a cycle in it. Follow up:Can you solve it without using extra space? 利用快慢指针,如果相遇则证明有环 注意边界条件: 如果只有一个node. public class Solution { public boolean hasCycle(ListNode head) { if(head==null |…
今天写代码的时候,需要遍历一个作为参数传递进来的容器, 当时顺手就加上了判空条件: if(null==list)return; 后来就像,不知道遍历(foreach)有没有帮我做这个工作: 下面看实验结果: public static void main(String[] args) { List<String> list =null; for (String s:list){ System.out.println(s); } } 运行时报空指针错误: Exception in thread…
[python]Leetcode每日一题-反转链表 II [题目描述] 给你单链表的头节点 head 和两个整数 left 和 right ,其中 left <= right .请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 . 示例1: 输入:head = [1,2,3,4,5], left = 2, right = 4 输出:[1,4,3,2,5] 示例2: 输入:head = [5], left = 1, right = 1 输出:[5] 提示: 链表中节点数…
[python]Leetcode每日一题-旋转链表 [题目描述] 给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置. 示例1: 输入:head = [1,2,3,4,5], k = 2 输出:[4,5,1,2,3] 示例2: 输入:head = [0,1,2], k = 4 输出:[2,0,1] 提示: 链表中节点的数目在范围 [0, 500] 内 -100 <= Node.val <= 100 0 <= k <= 2 * 10^9 [分析] 思路 由…
[python]Leetcode每日一题-删除排序链表中的重复元素 [题目描述] 存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 . 返回同样按升序排列的结果链表. 示例1: 输入:head = [1,1,2] 输出:[1,2] 示例2: 输入:head = [1,1,2,3,3] 输出:[1,2,3] 提示: 链表中节点数目在范围 [0, 300] 内 -100 <= Node.val <= 100 题目数据保证链表已经按升序排列…