mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Update 707.设计链表,添加C#版
This commit is contained in:
@ -1485,6 +1485,77 @@ impl MyLinkedList {
|
||||
}
|
||||
```
|
||||
|
||||
### C#
|
||||
```C#
|
||||
class ListNode
|
||||
{
|
||||
public int val;
|
||||
public ListNode next;
|
||||
public ListNode(int val) { this.val = val; }
|
||||
}
|
||||
public class MyLinkedList
|
||||
{
|
||||
ListNode dummyHead;
|
||||
int count;
|
||||
|
||||
public MyLinkedList()
|
||||
{
|
||||
dummyHead = new ListNode(0);
|
||||
count = 0;
|
||||
}
|
||||
|
||||
public int Get(int index)
|
||||
{
|
||||
if (index < 0 || count <= index) return -1;
|
||||
ListNode current = dummyHead;
|
||||
for (int i = 0; i <= index; i++)
|
||||
{
|
||||
current = current.next;
|
||||
}
|
||||
return current.val;
|
||||
}
|
||||
|
||||
public void AddAtHead(int val)
|
||||
{
|
||||
AddAtIndex(0, val);
|
||||
}
|
||||
|
||||
public void AddAtTail(int val)
|
||||
{
|
||||
AddAtIndex(count, val);
|
||||
}
|
||||
|
||||
public void AddAtIndex(int index, int val)
|
||||
{
|
||||
if (index > count) return;
|
||||
index = Math.Max(0, index);
|
||||
count++;
|
||||
ListNode tmp1 = dummyHead;
|
||||
for (int i = 0; i < index; i++)
|
||||
{
|
||||
tmp1 = tmp1.next;
|
||||
}
|
||||
ListNode tmp2 = new ListNode(val);
|
||||
tmp2.next = tmp1.next;
|
||||
tmp1.next = tmp2;
|
||||
}
|
||||
|
||||
public void DeleteAtIndex(int index)
|
||||
{
|
||||
|
||||
if (index >= count || index < 0) return;
|
||||
var tmp1 = dummyHead;
|
||||
for (int i = 0; i < index; i++)
|
||||
{
|
||||
tmp1 = tmp1.next;
|
||||
}
|
||||
tmp1.next = tmp1.next.next;
|
||||
count--;
|
||||
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
|
Reference in New Issue
Block a user