203. 移除链表元素
public ListNode removeElements ( ListNode head, int val) { ListNode dummy = new ListNode ( 0 ) ; dummy. next = head; ListNode p = dummy; while ( p. next != null ) { if ( p. next. val == val) { p. next = p. next. next; } else { p = p. next; } } return dummy. next;
}
707. 设计链表
class ListNode { int val; ListNode next; ListNode ( ) { } ; ListNode ( int val) { this . val = val; }
} class MyLinkedList { int size; ListNode dummy; public MyLinkedList ( ) { size = 0 ; dummy = new ListNode ( 0 ) ; } public int get ( int index) { if ( index < 0 || index >= size) { return - 1 ; } ListNode cur = dummy; for ( int i = index; i > 0 ; -- i) { cur = cur. next; } return cur. next. val; } public void addAtHead ( int val) { ListNode node = new ListNode ( val) ; node. next = dummy. next; dummy. next = node; size++ ; } public void addAtTail ( int val) { ListNode cur = dummy; ListNode node = new ListNode ( val) ; while ( cur. next != null ) { cur = cur. next; } cur. next = node; size++ ; } public void addAtIndex ( int index, int val) { if ( index > size) return ; ListNode cur = dummy; ListNode node = new ListNode ( val) ; for ( int i = index; i > 0 ; -- i) { cur = cur. next; } node. next = cur. next; cur. next = node; size++ ; } public void deleteAtIndex ( int index) { if ( index < 0 || index >= size) return ; ListNode cur = dummy; if ( index == 0 ) { dummy = dummy. next; } for ( int i = index; i > 0 ; -- i) { cur = cur. next; } cur. next = cur. next. next; size-- ; }
}
反转链表
双指针法
public static ListNode reverseList ( ListNode head) { ListNode pre = null ; ListNode cur = head; while ( cur != null ) { ListNode tmp = cur. next; cur. next = pre; pre = cur; cur = tmp; } return pre;
}
迭代法
public static ListNode reverseList ( ListNode head) { return reverse ( null , head) ;
} public static ListNode reverse ( ListNode pre, ListNode cur) { if ( cur == null ) { return pre; } ListNode tmp = cur. next; cur. next = pre; return reverse ( cur, tmp) ;
}