leetcode解题之24. Swap Nodes in Pairs java 版(成对翻转链表)

来源:互联网 发布:淘宝真空压缩袋 编辑:程序博客网 时间:2024/05/16 10:30

24. Swap Nodes in Pairs

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 maynot modify the values in the list, only nodes itself can be change

成对交换链表

自己的笨方法,AC,准备两个list,一个存放第奇数个结点,一个存放偶数个结点,取的时候反过来。合成一个,最后就是结果,注意最后需要把尾结点置空

public ListNode swapPairs(ListNode head) {if (head == null)return null;List<ListNode> first = new ArrayList<>();List<ListNode> second = new ArrayList<>();ListNode cur = head;ListNode ph = new ListNode(0);int i = 0;while (cur != null) {if ((i & 1) == 0)first.add(cur);elsesecond.add(cur);cur = cur.next;i++;}cur = ph;while (!first.isEmpty() && !second.isEmpty()) {cur.next = second.get(0);cur = cur.next;cur.next = first.get(0);cur = cur.next;first.remove(0);second.remove(0);}if (!second.isEmpty()) {cur.next = second.get(0);cur = cur.next;}if (!first.isEmpty()) {cur.next = first.get(0);cur = cur.next;}cur.next = null;return ph.next;}
参考代码:

public ListNode swapPairs(ListNode head) {if (head == null || head.next == null)return head;// 防止丢链ListNode tmpHead = new ListNode(0);// ptr1始终指向需要交换的pair的前面一个node,ListNode ptr1 = tmpHead;// ptr2始终指向需要交换的pair的第一个node。ListNode ptr2 = head;// 当链表长度为奇数时,ptr2.next可能为null;// 当链表长度为偶数时,ptr2可能为null。while (ptr2 != null && ptr2.next != null) {// 需要用一个临时指针nextstart, 指向下一个,// 需要交换的pair的第一个node保证下一次交换的正确进行。ListNode nextstart = ptr2.next.next;ptr2.next.next = ptr2;ptr1.next = ptr2.next;ptr2.next = nextstart;ptr1 = ptr2;ptr2 = nextstart;}return tmpHead.next;}



0 0