c#-单链表
namespace MyLink; public class MyLinkedList { private int _size{get;set;} public class MyTreeNode{ public int val{get;set;} public MyTreeNode next{get;set;} public MyTreeNode(int val) { this.val = val; } } public MyTreeNode head{get;set;} public MyLinkedList() { head = new MyTreeNode(0); //虚拟头结点 this._size = 0; } public int Get(int index) { if(index < 0 || index >= this._size) return -1; var cur = head.next; while(index != 0) // 举个案例来测试边界 如 index=0,这个循环就不会执行 { cur = cur.next; index--; } return cur.val; } public void AddAtHead(int val) { var newHead = new MyTreeNode(val); newHead.next = head.next; head.next = newHead; this._size ++; } public void AddAtTail(int val) { var cur = head; // 指向虚拟节点 * while(cur.next != null) { cur = cur.next; } cur.next = new MyTreeNode(val); this._size++; } public void AddAtIndex(int index, int val) { var newNode = new MyTreeNode(val); var cur = head; while(index != 0) { cur = cur.next; if(cur == null) break; index --; } if(cur != null) { newNode.next = cur.next; cur.next = newNode; this._size++; } } public void DeleteAtIndex(int index) { if(index < this._size){ var cur = head; while(index != 0) { cur = cur.next; if(cur == null) return; index--; } if (cur != null) { cur.next = cur.next.next; this._size--; } } } } /** * 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); */
力扣707