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; }