[LeetCode]Swap Nodes in Pairs

来源:互联网 发布:mac版lol国服何时出 编辑:程序博客网 时间:2024/06/06 04:56

题目描述

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.

给你一个链表,交换相邻的两个链表

解题思路

  1. 交换相邻两个链表节点,并将交换的尾节点记录;
  2. 将上次的尾节点指向本次交换后的头节点;
  3. 重复上述步骤;
以上需要注意如果节点个数为奇数的情况。

代码

public ListNode swapPairs(ListNode head) {ListNode node = head, result = head;ListNode firstNode = head;ListNode secondNode = head;ListNode lastNode = head;while (node != null) {firstNode = node;secondNode = node.next;if (secondNode == null) {//考虑节点个数为奇数的情况secondNode = node;} else {firstNode.next = secondNode.next;secondNode.next = firstNode;}if (firstNode == head) {//第一次交换时,记录最终交换完的头节点result = secondNode;} else {//上一次交换的尾节点指向本次交换完的头节点lastNode.next = secondNode;}lastNode = firstNode;node = firstNode.next;}return result;}


0 0