您的位置:首页 > Web前端 > Node.js

LeetCode-24. Swap Nodes in Pairs

2017-02-17 11:37 323 查看
一、问题描述

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.

二、解题思路

从链表头开始两个元素一组,交换彼此的位置,并返回交换后的链表。主要是考察链表的操作。



cur的下一个元素指向head的下一个元素,将head的下一个元素指向second的下一个元素,将second的下一个元素指向head,head右移一个单位,cur右移两个单位。主要是处理好需要交换的两元素的前部分和后部分,防止出现断层。

三、代码

/**
* 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 result=new ListNode(0);
result.next=head;
ListNode cur=result;
while(head!=null && head.next!=null){
ListNode second=head.next;
cur.next=second;
head.next=second.next;
second.next=head;
head=head.next;
cur=cur.next.next;
}
return result.next;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode result = new ListNode(0);
result.next = head;
ListNode former = result;
while(head != null && head.next != null){
ListNode tem = head.next.next;//tem指向位置3,因为交换1和2,首先要保存其后的链表
head.next.next = head;//将2指向1
former.next = head.next;//将0指向2,此时0-》2-》1-》2
former = head;//重新赋值former和head变量,准备下一次的循环
former.next = tem;
head = tem;
}
return result.next;
}
}
重新组织思路写了一遍,在此次更新中,程序一开始,former指向的是0,head 指向的是1,第一次循环中tem变量指向的是3,。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: