单向链表设计
package 日常Java 程序测试. 代码随想录. 链表; public class __707设计链表__单向链表设计 { class MyLinkedList { int val; MyLinkedList next; int size; public MyLinkedList ( ) { size = 0 ; val = 0 ; next = new MyLinkedList ( 0 ) ; } public MyLinkedList ( int val) { this . val = val; } public int get ( int index) { if ( index < 0 || index > size) { return - 1 ; } MyLinkedList curNode = next; for ( int i= 0 ; i<= index; i++ ) { curNode = curNode. next; } return curNode. 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 > size) { return ; } if ( index < 0 ) { index = 0 ; } size++ ; MyLinkedList pred = next; for ( int i= 0 ; i< index; i++ ) { pred = pred. next; } MyLinkedList toAdd = new MyLinkedList ( val) ; toAdd. next = pred. next; pred. next = toAdd; } public void deleteAtIndex ( int index) { if ( index < 0 || index >= size) { return ; } size-- ; if ( index < 0 ) { index = 0 ; } if ( index == 0 ) { next = next. next; return ; } MyLinkedList pred = next; for ( int i= 0 ; i< index; i++ ) { pred = pred. next; } pred. next = pred. next. next; } }
}
双链表
class ListNode { int val; ListNode next, prev; ListNode ( ) { } ; ListNode ( int val) { this . val = val; }
} class MyLinkedList { int size; ListNode head, tail; public MyLinkedList ( ) { this . size = 0 ; this . head = new ListNode ( 0 ) ; this . tail = new ListNode ( 0 ) ; head. next= tail; tail. prev= head; } public int get ( int index) { if ( index< 0 || index>= size) { return - 1 ; } ListNode cur = this . head; if ( index >= size / 2 ) { cur = tail; for ( int i= 0 ; i< size- index; i++ ) { cur = cur. prev; } } else { for ( int i= 0 ; i<= index; i++ ) { cur = cur. next; } } return cur. 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> size) { return ; } if ( index< 0 ) { index = 0 ; } size++ ; ListNode pre = this . head; for ( int i= 0 ; i< index; i++ ) { pre = pre. next; } ListNode newNode = new ListNode ( val) ; newNode. next = pre. next; pre. next. prev = newNode; newNode. prev = pre; pre. next = newNode; } public void deleteAtIndex ( int index) { if ( index< 0 || index>= size) { return ; } size-- ; ListNode pre = this . head; for ( int i= 0 ; i< index; i++ ) { pre = pre. next; } pre. next. next. prev = pre; pre. next = pre. next. next; }
}