Update linked_list.md to add csharp code.

This commit is contained in:
ming 2022-12-16 16:28:19 +08:00
parent aa868cfa3d
commit 0a0374efa0

View File

@ -91,7 +91,13 @@ comments: true
=== "C#"
```csharp title=""
// 链表结点类
class ListNode
{
int val; // 结点值
ListNode next; // 指向下一结点的引用
ListNode(int x) => val = x; //构造函数
}
```
**尾结点指向什么?** 我们一般将链表的最后一个结点称为「尾结点」,其指向的是「空」,在 Java / C++ / Python 中分别记为 `null` / `nullptr` / `None` 。在不引起歧义下,本书都使用 `null` 来表示空。
@ -202,7 +208,18 @@ comments: true
=== "C#"
```csharp title=""
// 初始化链表 1 -> 3 -> 2 -> 5 -> 4
// 初始化各结点
n0 = new ListNode(1);
n1 = new ListNode(3);
n2 = new ListNode(2);
n3 = new ListNode(5);
n4 = new ListNode(4);
// 构建引用指向
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
```
## 链表优点
@ -331,7 +348,24 @@ comments: true
=== "C#"
```csharp title=""
// 在链表的结点 n0 之后插入结点 P
void Insert(ListNode n0, ListNode P)
{
ListNode n1 = n0.next;
n0.next = P;
P.next = n1;
}
// 删除链表的结点 n0 之后的首个结点
void Remove(ListNode n0)
{
if (n0.next == null)
return;
// n0 -> P -> n1
ListNode P = n0.next;
ListNode n1 = P.next;
n0.next = n1;
}
```
## 链表缺点
@ -422,7 +456,17 @@ comments: true
=== "C#"
```csharp title=""
// 访问链表中索引为 index 的结点
ListNode Access(ListNode head, int index)
{
for (int i = 0; i < index; i++)
{
head = head.next;
if (head == null)
return null;
}
return head;
}
```
**链表的内存占用多。** 链表以结点为单位,每个结点除了保存值外,还需额外保存指针(引用)。这意味着同样数据量下,链表比数组需要占用更多内存空间。
@ -526,7 +570,19 @@ comments: true
=== "C#"
```csharp title=""
// 在链表中查找值为 target 的首个结点
int Find(ListNode head, int target)
{
int index = 0;
while (head != null)
{
if (head.val == target)
return index;
head = head.next;
index++;
}
return -1;
}
```
## 常见链表类型
@ -619,7 +675,13 @@ comments: true
=== "C#"
```csharp title=""
// 双向链表结点类
class ListNode {
int val; // 结点值
ListNode next; // 指向后继结点的指针(引用)
ListNode prev; // 指向前驱结点的指针(引用)
ListNode(int x) => val = x; // 构造函数
}
```
![linkedlist_common_types](linked_list.assets/linkedlist_common_types.png)