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 /** 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 * @param k an integer 13 * @return a ListNode 14 */ 15 public ListNode reverseKGroup(ListNode head, int k) { 16 if (head == null || size(head) < k) return head; 17 18 ListNode prev = null; 19 ListNode current = head; 20 ListNode next = null; 21 int i = 1; 22 while (current != null && i <= k) { 23 next = current.next; 24 current.next = prev; 25 prev = current; 26 current = next; 27 i++; 28 } 29 30 head.next = reverseKGroup(current, k); 31 return prev; 32 } 33 34 private int size(ListNode head) { 35 int total = 0; 36 while(head != null) { 37 total++; 38 head = head.next; 39 } 40 return total; 41 } 42 }
时间: 2024-10-16 09:27:00