swapPairs

来源:互联网 发布:淘宝玻璃茶具套装 编辑:程序博客网 时间:2024/06/05 06:57

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

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.


public class Solution {
public ListNode swapPairs(ListNode head) {
ListNode start = new ListNode(0);
start.next = head;
for(ListNode cur = start; cur.next != null && cur.next.next != null; cur = cur.next.next) {
cur.next = swap(cur.next, cur.next.next);
}
return start.next;
}
private Listnode swap(ListNode next1, ListNode next2) {
next1.next = next2.next;
next2.next = next1;
return next2;
}
}
运用了递归的思想,解决问题前化大为小,思考时候是否能够重复某一个小的步骤来解决一个问题。@mike3 from leetcode discusstion

next: Reverse Nodes in k-Group

0 0
原创粉丝点击