1. C#中构造链表的简要逻辑:
public class Node
{
public int value;
public Node next;
public Node(int value)
{
this.value = value;
next = null;
}
}
2.遍历链表,获取长度:
public static int GetLength(Node head)
{
int length = 0;
Node node = head;
while (node != null)//注意不是 while (node.next != null)
{
length++;
node = node.next;
}
return length;
}
3.在链表中的指定位置添加一个元素
public static Node AddWithPosition(Node head, Node nodeInsert, int position)
{
if (head == null)
{
head = nodeInsert;
return head;
}
if (position > GetLength(head) + 1 || position < 1)
{
Console.WriteLine("越界");
return head;
}
//头
if (position == 1)
{
nodeInsert.next = head;
head = nodeInsert;
return head;
}
//尾
if (position == GetLength(head) + 1)
{
Node node = head;
while (node.next != null)
{
node = node.next;
}
node.next = nodeInsert;
return head;
}
//中间
int count = 1;//count从1开始!!!不是0
Node pNode = head;
while (count < position - 1)
{
pNode = pNode.next;
count++;
}
nodeInsert.next = pNode.next;
pNode.next = nodeInsert;
return head;
}
4.有序链表增加一个元素,使其仍保持有序(以降序为例,升序逻辑相同)
public static Node AddWithSortDes(Node head, Node nodeInsert)
{
if(head == null)
{
head = nodeInsert;
return head;
}
//插入的元素大于等于头部节点的元素,则插到链表头
if (nodeInsert.value >= head.value)
{
nodeInsert.next = head;
head = nodeInsert;
return head;
}
//中间
Node n = head;
while(n.next != null)
{
//寻找到一个比前面小,但是比后面大的位置
if (n.value >= nodeInsert.value && n.next.value <= nodeInsert.value)
{
nodeInsert.next = n.next;
n.next = nodeInsert;
return head;
}
n = n.next;
}
//找不到位置就插入到尾部
n.next = nodeInsert;
return head;
}
5.删除链表中的特定位置的元素
public static Node RemoveWithPosition(Node head, int position)
{
if (position > GetLength(head) || position < 1)
{
Console.WriteLine("位置错误");
}
if (head == null || position == 1 && GetLength(head) == 1)
return null;
if(position == 1)
{
head = head.next;
return head;
}
else
{
Node n = head;
int index = 1;
while(index < position -1)
{
n = n.next;
index++;
}
n.next = n.next.next;
}
return head;
}