• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

LeetCode: Linked List Cycle

双指针的简单题

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) {
12         // IMPORTANT: Please reset any member data you declared, as
13         // the same Solution instance will be reused for each test case.
14         if (head == NULL) return false;
15         ListNode *p, *q;
16         p = q = head;
17         while (q) {
18             q = q->next;
19             if (q == NULL) break;
20             if (p == q) return true;
21             p = p->next;
22             q = q->next;
23         }
24         return false;
25     }
26 };

 C#

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     public int val;
 5  *     public ListNode next;
 6  *     public ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public bool HasCycle(ListNode head) {
14         if (head == null) return false;
15         ListNode p = head, q = head;
16         while (q != null) {
17             q = q.next;
18             if (q == null) break;
19             if (p == q) return true;
20             p = p.next;
21             q = q.next;
22         }
23         return false;
24     }
25 }
View Code

 

posted @ 2013-11-14 13:22  ying_vincent  阅读(133)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3