leetcode刷题_OJ 24

Given a linked list, swap every two adjacent nodes and return its head.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:

Your algorithm should use only constant extra space.
You may not modify the values in the list's nodes, only nodes itself may be changed.

题目的主要意思:在不修改结点值和可以另外开辟空间的前提下将列表中两两变量互换位置。虽然修改结点值也可以过,但是始终不合要求,也辜负了题目想要考我们链表的基本操作的心愿。

这题对于不熟悉链表的人是一个很好的题目,因为如果捋不清链表元素交换位置后前后各元素的变化,真的看个代码都看到头晕,下面我以我自己看到的一种比较好理解的方法来讲解这道题的一个很简单的思路。

例:A->B->C->D,假设我们要交换B和C的位置,那么此时链表有3个最基本的操作:

1、A指向C

2、B指向D

3、C指向B

完成了上面3个基本操作,也就换成了B和C的互换,但是为了能够继续交换下去,此时指向A的指针要往后移两位。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode preNode=new ListNode(0);
        preNode.next=head;
        ListNode temp=preNode;
        while(temp.next != null && temp.next.next != null){
        	ListNode node1=temp.next;//B
        	ListNode node2=temp.next.next;//C
        	temp.next=node2;//A->C
        	node1.next=node2.next;//B->D
        	node2.next=node1;//C->B
        	temp=temp.next.next;
        }
        return preNode.next;
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值