LeetCode 24 Swap Nodes in Pairs

来源:互联网 发布:数据安全责任承诺书 编辑:程序博客网 时间:2024/06/11 18:01

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 ListNode swapPairs(ListNode head) {if (head == null || head.next == null) return head;ListNode result = head.next;ListNode pre = new ListNode(-1);while (head != null && head.next != null) {ListNode even = head.next;head.next = even.next;even.next = head;pre.next = even;pre = head;head = head.next;}return result;}

另外,可以使用递归:

public ListNode swapPairs(ListNode head) {if (head == null || head.next == null) return head;ListNode even = head.next;head.next = swapPairs(even.next);even.next = head;return even;}


0 0
原创粉丝点击