Day4
This commit is contained in:
11
142. Linked List Cycle II/142. Linked List Cycle II.csproj
Normal file
11
142. Linked List Cycle II/142. Linked List Cycle II.csproj
Normal file
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<RootNamespace>_142._Linked_List_Cycle_II</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
37
142. Linked List Cycle II/ListNode.cs
Normal file
37
142. Linked List Cycle II/ListNode.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
namespace _142._Linked_List_Cycle_II;
|
||||
|
||||
//Definition for singly-linked list.
|
||||
public class ListNode
|
||||
{
|
||||
public int val;
|
||||
public ListNode? next;
|
||||
public ListNode(int val = 0, ListNode? next = null)
|
||||
{
|
||||
this.val = val;
|
||||
this.next = next;
|
||||
}
|
||||
|
||||
public static ListNode Create(int[] nums)
|
||||
{
|
||||
ListNode l = new ListNode(nums[0]);
|
||||
ListNode cur = l;
|
||||
for (int i = 1; i < nums.Length; i++)
|
||||
{
|
||||
cur.next = new ListNode(nums[i]);
|
||||
cur = cur.next;
|
||||
}
|
||||
return l;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
List<int> list = new List<int>();
|
||||
ListNode? cur = this;
|
||||
while (cur != null)
|
||||
{
|
||||
list.Add(cur.val);
|
||||
cur = cur.next;
|
||||
}
|
||||
return String.Join(" ", list);
|
||||
}
|
||||
}
|
||||
15
142. Linked List Cycle II/Program.cs
Normal file
15
142. Linked List Cycle II/Program.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
namespace _142._Linked_List_Cycle_II
|
||||
{
|
||||
internal class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
var l1 = new ListNode(3);
|
||||
var l2 = new ListNode(2);
|
||||
|
||||
l1.next = l2;
|
||||
l2.next = l1;
|
||||
Console.WriteLine(new Solution().DetectCycle(l1)?.val);
|
||||
}
|
||||
}
|
||||
}
|
||||
28
142. Linked List Cycle II/Solution.cs
Normal file
28
142. Linked List Cycle II/Solution.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
namespace _142._Linked_List_Cycle_II;
|
||||
|
||||
public class Solution
|
||||
{
|
||||
public ListNode? DetectCycle(ListNode head)
|
||||
{
|
||||
ListNode? cur = head;
|
||||
int bit = 1 << 28;
|
||||
int curAbs = 0;
|
||||
while (cur!=null && (curAbs & bit) == 0)
|
||||
{
|
||||
cur.val ^= bit;
|
||||
cur = cur.next;
|
||||
if(cur != null)
|
||||
curAbs = cur.val < 0 ? (cur.val * -1) : cur.val;
|
||||
}
|
||||
cur = head;
|
||||
curAbs = cur.val < 0 ? (cur.val * -1) : cur.val;
|
||||
while (cur != null && (curAbs & bit) != 0)
|
||||
{
|
||||
cur.val ^= bit;
|
||||
cur = cur.next;
|
||||
if (cur != null)
|
||||
curAbs = cur.val < 0 ? (cur.val * -1) : cur.val;
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user