您的位置:首页 > Web前端 > Node.js

Swap Nodes & Reverse Nodes in k-Group

2016-07-05 12:24 381 查看
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
.

分析:使用递归,方便又快捷。

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @return a ListNode
*/
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;

ListNode prev = head;
ListNode current = head.next;
head = current.next;
current.next = prev;

prev.next = swapPairs(head);

return current;
}
}


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


/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @param k an integer
* @return a ListNode
*/
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || size(head) < k) return head;

ListNode prev = null;
ListNode current = head;
ListNode next = null;
int i = 1;
while (current != null && i <= k) {
next = current.next;
current.next = prev;
prev = current;
current = next;
i++;
}

head.next = reverseKGroup(current, k);
return prev;
}

private int size(ListNode head) {
int total = 0;
while(head != null) {
total++;
head = head.next;
}
return total;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: