设计链表.

leetcode :707题

这题基本涵盖链表的的常用操作,

  • 获取第n个节点的值(从零开始)
  • 头部插入节点
  • 尾部插入节点
  • 第n个节点前插入节点
  • 删除第n个节点

C#:

public class MyLinkedList {

    public int count {get;set;}
    private  Node dummyHead;
    public MyLinkedList() {
        dummyHead = new Node(0);
        count=0;
    }
    
    public int Get(int index) {
        //判断下标是否为合法区间
        if(index<0 || index >=count)
        {
            return -1;
        }
        var current = dummyHead.next;
        while(index != 0 )
        {
            current=current.next;
            index--;
        }
        return current.value;
    }
    
    public void AddAtHead(int val) {
        var newNode = new Node(val);
        //注意要先将新节点指向头节点
        //再用虚拟头节点指向新节点,不然找不到原来的头节点了
        newNode.next = dummyHead.next;
        dummyHead.next = newNode;
        count++;
    }
    
    public void AddAtTail(int val) {
        
        var current = dummyHead;

        while(current.next!= null)
        {
            current = current.next;
        }
        var newNode = new Node(val);
        current.next = newNode;
        count++;
    }
    
    public void AddAtIndex(int index, int val) {
        if(index < 0 || index > count)
        {
            return;
        }
        var newNode = new Node(val);
        var current = dummyHead;
        while(index-- != 0)
        {
            current = current.next;
        }
        newNode.next = current.next;
        current.next = newNode;
        count++;
    }
    
    public void DeleteAtIndex(int index) {
        if(index<0 || index >= count)
        {
            return;
        }

       var current = dummyHead;
        while(index!= 0)
        {
            current =current.next;
            index --;
        }
        current.next = current.next.next;
        count--;
    }
    public class Node
    {
        public int value {get; set;}
        public Node next {get;set;}
        public Node(int val)
        {
            this.value=val;
            this.next = null;
        }
    }
}

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList obj = new MyLinkedList();
 * int param_1 = obj.Get(index);
 * obj.AddAtHead(val);
 * obj.AddAtTail(val);
 * obj.AddAtIndex(index,val);
 * obj.DeleteAtIndex(index);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值