Skip to content

Instantly share code, notes, and snippets.

@rajibdpi
Created October 27, 2023 18:02
Show Gist options
  • Save rajibdpi/eb9b270a5ee299701708a2ad37fd667f to your computer and use it in GitHub Desktop.
Save rajibdpi/eb9b270a5ee299701708a2ad37fd667f to your computer and use it in GitHub Desktop.
designLinedList
public class ListNode
{
public int Val;
public ListNode Next;
public ListNode(int x = 0, ListNode Next = null)
{
Val = x;
Next = Next;
}
}
public class MyLinkedList {
int length;
ListNode dummyHead;
public MyLinkedList() {
length = 0;
dummyHead = new ListNode();
}
public int Get(int index) {
if (index < 0 || index >= length) return -1;
var currentHead = dummyHead.Next;
while (index > 0)
{
index--;
currentHead = currentHead.Next;
}
return currentHead.Val;
}
public void AddAtHead(int val) {
AddAtIndex(0, val);
}
public void AddAtTail(int val) {
AddAtIndex(length, val);
}
public void AddAtIndex(int index, int val) {
if (index < 0 || index > length) return;
var currentHead = dummyHead;
while (index > 0)
{
index--;
currentHead = currentHead.Next;
}
var newNode = new ListNode(val, currentHead.Next);
currentHead.Next = newNode;
length++;
}
public void DeleteAtIndex(int index) {
if (index < 0 || index >= length) return;
var currentHead = dummyHead;
while (index > 0)
{
index--;
currentHead = currentHead.Next;
}
currentHead.Next = currentHead.Next.Next;
length--;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment