编程导航算法通关村第1关 | 青铜教程学习总结

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值