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);
 */