Linked List Cycle
2015-09-09 21:46
225 查看
题目描述:Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解题思路:由于不使用额外的空间,所以可以在扫描节点之后,让节点后继指针指向头节点,如果以后扫描的后继节点与头节点相同,有环。
Java实现:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
/*Set<ListNode> set=new HashSet<ListNode>();
ListNode p=head;
while(p!=null){
if(set.contains(p)) return true;
else set.add(p);
p=p.next;
}
return false;*/
if(head==null) return false;
ListNode p=head,q=head;
while(p.next!=null){
if(p.next==head) return true;
q=p;
p=p.next;
q.next=head;
}
return false;
}
}原题题目:https://leetcode.com/problems/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?
解题思路:由于不使用额外的空间,所以可以在扫描节点之后,让节点后继指针指向头节点,如果以后扫描的后继节点与头节点相同,有环。
Java实现:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
/*Set<ListNode> set=new HashSet<ListNode>();
ListNode p=head;
while(p!=null){
if(set.contains(p)) return true;
else set.add(p);
p=p.next;
}
return false;*/
if(head==null) return false;
ListNode p=head,q=head;
while(p.next!=null){
if(p.next==head) return true;
q=p;
p=p.next;
q.next=head;
}
return false;
}
}原题题目:https://leetcode.com/problems/linked-list-cycle/
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解