Java实现letcode SwapNodeInPairs

  |   0 评论   |   101 浏览

[[LeetCode] 24. Swap Nodes in Pairs 成对交换节点]

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list’s nodes, only nodes itself may be changed.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.
基本的链表操作题,我们可以分别用递归和迭代来实现。
循环实现:主要需要记录当前的节点,当然应该有简洁的,更清晰的思路
/**

  • 循环实现,需要带入前面节点的信息

  • @param node

  • @return

*/

public static Node swapT(Node node) {

Node head = node;

Node m = null;

Node n = null;

int i = 0;

while (node != null && node.next != null) {

m = node.next;

node.next = m.next;

m.next = node;

if (i == 0) {

n = node;

head = m;

} else {

n.next = m;

n = node;

}

node = node.next;

i++;

}

return head;

}

第二种是迭代,这个思路比较清晰
/**

  • 递归实现

  • @param node

  • @return

*/

public static Node swap(Node node) {

if (node == null || node.next == null) {

return node;

}

Node m = node.next;

node.next = swap(node.next.next);

m.next = node;

return m;

}

评论

发表评论

validate