24. Swap Nodes & Reverse Nodes in k-Group
Swap Nodes |
Given a linked list, swap every two adjacent nodes and return its head.
Example
Given 1->2->3->4, you should return the list as 2->1->4->3.
分析:使用递归,方便又快捷。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 /** 11 * @param head a ListNode 12 * @return a ListNode 13 */ 14 public ListNode swapPairs(ListNode head) { 15 if (head == null || head.next == null) return head; 16 17 ListNode prev = head; 18 ListNode current = head.next; 19 head = current.next; 20 current.next = prev; 21 22 prev.next = swapPairs(head); 23 24 return current; 25 } 26 }
Reverse Nodes in k-Group
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed. Only constant memory is allowed.
Example
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
1 class Solution { 2 public ListNode reverseKGroup(ListNode head, int k) { 3 if (head == null || !hasKElements(head, k)) return head; 4 5 ListNode prev = null; 6 ListNode current = head; 7 ListNode next = null; 8 int i = 1; 9 while (i <= k) { 10 next = current.next; 11 current.next = prev; 12 prev = current; 13 current = next; 14 i++; 15 } 16 17 head.next = reverseKGroup(current, k); 18 return prev; 19 } 20 21 private boolean hasKElements(ListNode head, int k) { 22 while(k >= 1) { 23 if (head == null) return false; 24 k--; 25 head = head.next; 26 } 27 return true; 28 } 29 }

浙公网安备 33010602011771号