Day7
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<RootNamespace>_19._Remove_Nth_Node_From_End_of_List</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
37
19. Remove Nth Node From End of List/ListNode.cs
Normal file
37
19. Remove Nth Node From End of List/ListNode.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
namespace _19._Remove_Nth_Node_From_End_of_List;
|
||||
|
||||
//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);
|
||||
}
|
||||
}
|
||||
18
19. Remove Nth Node From End of List/Program.cs
Normal file
18
19. Remove Nth Node From End of List/Program.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
namespace _19._Remove_Nth_Node_From_End_of_List;
|
||||
|
||||
internal class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
ListNode l1 = new ListNode(1);
|
||||
ListNode l2 = new ListNode(2);
|
||||
ListNode l3 = new ListNode(3);
|
||||
ListNode l4 = new ListNode(4);
|
||||
|
||||
//l1.next = l2;
|
||||
//l2.next = l3;
|
||||
//l3.next = l4;
|
||||
|
||||
Console.WriteLine(new Solution().RemoveNthFromEnd(l1, 1));
|
||||
}
|
||||
}
|
||||
29
19. Remove Nth Node From End of List/Solution.cs
Normal file
29
19. Remove Nth Node From End of List/Solution.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
namespace _19._Remove_Nth_Node_From_End_of_List;
|
||||
|
||||
public class Solution
|
||||
{
|
||||
public ListNode? RemoveNthFromEnd(ListNode head, int n)
|
||||
{
|
||||
if (head.next == null)
|
||||
return null;
|
||||
ListNode? left = null;
|
||||
ListNode? right = head;
|
||||
n--;
|
||||
while (n-- > 0)
|
||||
right = right!.next;
|
||||
while (right!.next != null)
|
||||
{
|
||||
if (left == null)
|
||||
left = head;
|
||||
else
|
||||
left = left.next;
|
||||
right = right.next;
|
||||
}
|
||||
if (left != null)
|
||||
{
|
||||
left.next = left.next!.next;
|
||||
return head;
|
||||
}
|
||||
return head.next;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user