-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathLinkedLists-InsertNthNode.cs
More file actions
48 lines (36 loc) · 967 Bytes
/
LinkedLists-InsertNthNode.cs
File metadata and controls
48 lines (36 loc) · 967 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
public partial class Node
{
public int Data;
public Node Next;
public Node(int data)
{
this.Data = data;
this.Next = null;
}
public static Node InsertNth(Node head, int index, int data)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), "Index is out of the range of the list.");
var newNode = new Node(data);
if (index == 0)
{
newNode.Next = head;
return newNode;
}
var current = head;
int count = 0;
while (current != null && count < index - 1)
{
current = current.Next;
count++;
}
if (current == null)
{
throw new ArgumentOutOfRangeException(nameof(index), "Index is out of the range of the list.");
}
newNode.Next = current.Next;
current.Next = newNode;
return head;
}
}