LeetCode : Swap Nodes in Pairs [java]

来源:互联网 发布:手机防盗报警软件 编辑:程序博客网 时间:2024/06/14 01:13

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.

思路:纯链表操作,使用额外节点记录"指针",主要需要记录的是:当前交换的两个节点,两个节点后的节点(如果有的话)以及构建新链表的"指针".

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode swapPairs(ListNode head) {ListNode myHead = new ListNode(-1);ListNode myPointer = myHead;while (head != null) {ListNode next2 = head.next;if (next2 == null) {myPointer.next = head;break;} else {next2 = next2.next;ListNode qian = head;ListNode hou = head.next;qian.next = hou.next;hou.next = qian;myPointer.next = hou;myPointer = myPointer.next.next;head = next2;}}return myHead.next;    }}


1 0
原创粉丝点击