题目
方法一:单向链表实现
新增或删除一个位置的节点==找到这个位置的前一个节点即可
class MyLinkedList { int size; ListNode head; public MyLinkedList ( ) { size = 0 ; head = new ListNode ( 0 ) ; } public int get ( int index) { if ( index < 0 || index > size- 1 ) return - 1 ; ListNode pre = head; while ( index >= 0 ) { pre = pre. next; index -- ; } return pre. val; } public void addAtHead ( int val) { addAtIndex ( 0 , val) ; } public void addAtTail ( int val) { addAtIndex ( size, val) ; } public void addAtIndex ( int index, int val) { if ( index < 0 || index > size) return ; ListNode pre = head; while ( index > 0 ) { pre = pre. next; index -- ; } ListNode cur = new ListNode ( val) ; cur. next = pre. next; pre. next = cur; size++ ; } public void deleteAtIndex ( int index) { if ( index < 0 || index > size- 1 ) return ; ListNode pre = head; while ( index > 0 ) { pre = pre. next; index -- ; } pre. next = pre. next. next; size-- ; }
} class ListNode { int val; ListNode next; public ListNode ( int val) { this . val = val; }
}
方法二: