24.?兩兩交換鏈表中的節點
迭代方法
public static ListNode swapPairs ( ListNode head) { ListNode dummy = new ListNode ( 0 ) ; dummy. next = head; ListNode cur = dummy; while ( cur. next != null && cur. next. next != null ) { ListNode tmp1 = cur. next; ListNode tmp2 = tmp1. next. next; cur. next = tmp1. next; tmp1. next. next = tmp1; tmp1. next = tmp2; cur = tmp1; } return dummy. next;
}
遞歸方法
public static ListNode swapPairs ( ListNode head) { if ( head == null || head. next == null ) return head; ListNode rest = head. next. next; ListNode newHead = head. next; newHead. next = head; head. next = swapPairs ( rest) ; return newHead;
}
19.?刪除鏈表的倒數第 N 個結點
快慢指針思想 先讓fast指針走n
步,然后快慢指針同時移動,當快指針為null
,則找到倒數第n
個節點
public static ListNode removeNthFromEnd ( ListNode head, int n) { ListNode dummy = new ListNode ( - 1 ) ; dummy. next = head; ListNode slow = dummy; ListNode fast = dummy; for ( int i = n+ 1 ; i > 0 && fast!= null ; i-- ) { fast = fast. next; } while ( fast != null ) { slow = slow. next; fast = fast. next; } slow. next = slow. next. next; return dummy. next;
}
面試題 鏈表相交
public static ListNode getIntersectionNode ( ListNode headA, ListNode headB) { ListNode pA = headA; ListNode pB = headB; if ( pA == null || pB == null ) return null ; while ( pA != pB) { pA = pA == null ? headB : pA. next; pB = pB == null ? headA : pB. next; } return pA;
}
142.?環形鏈表 II
當快慢節點相遇后,將快節點移動到鏈表頭部,快節點和慢節點相遇的地方就是入口
public ListNode detectCycle ( ListNode head) { ListNode fast = head; ListNode slow = head; while ( true ) { if ( fast == null || fast. next == null ) return null ; slow = slow. next; fast = fast. next. next; if ( slow == fast) { break ; } } fast = head; while ( slow != fast) { slow = slow. next; fast = fast. next; } return fast; }