成对交换单链表的结点

原题

  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.

题目大意

  给定一个单链表,成对交换两个相邻的结点。算法法应该做常量辅助空间,不能改结点的值,只能交换结点。

解题思路

  使用一个头结点root来辅助操作,对要进行交换的链表,每两个的位置进行交换,并且把交换后的结点接到root的链表上,直到所有的结点都处理完。

代码实现

结点类

public class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
        next = null;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

算法实现类

public class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode node = new ListNode(0); // 头结点
        node.next = head;

        // p指向新的链表的尾结点
        ListNode p = node;
        ListNode tmp;

        // 每两个进行操作
        while (p.next != null && p.next.next != null) {
            // 记录下一次要进行处理的位置
            tmp = p.next.next;
            // 下面三句完成两个结点交换
            p.next.next = tmp.next;
            tmp.next = p.next;
            p.next = tmp;
            // 指向返回链表的新的尾结点
            p = tmp.next;
        }

        head = node.next;
        node.next = null;

        return head;
    }
}

 

 

背景: 交换一个链表中,连续的两个节点的位置。比如:1->2->3->4 返回2->1->4->3

 

 

[java] view plain copy

print?在CODE上查看代码片派生到我的代码片

  1. /** 
  2.  * Definition for singly-linked list. 
  3.  * public class ListNode { 
  4.  *     int val; 
  5.  *     ListNode next; 
  6.  *     ListNode(int x) { val = x; } 
  7.  * } 
  8.  */  

 

[java] view plain copy

print?在CODE上查看代码片派生到我的代码片

  1. public static ListNode swapPairs(ListNode head){  
  2.         if(head == null || head.next == null)return head;   
  3.         ListNode dummy = new ListNode(0);  
  4.         ListNode l = head.next;  
  5.         dummy.next = head;  
  6.         while(dummy.next != null && dummy.next.next != null){  
  7.             ListNode first = dummy.next;  
  8.             ListNode second = dummy.next.next;  
  9.               
  10.             first.next = second.next;  
  11.             second.next = first;  
  12.             dummy.next = second;  
  13.               
  14.             dummy = dummy.next.next;  
  15.         }  
  16.           
  17.         return l;  
  18.     }  

 

 

 

 

 

首先我们需要一个多余的节点来存储要交换的两个节点的第一个节点上一级, 然后对着两个节点进行交换, 再完成两个节点的交换之后, 我们需要将之前存储的第一个节点的上一级进行赋值,使其指向交换后的第一个节点,(这个过程很重要,如果缺失了这一过程,那么我们将丢失链接)。 然后就这个多余节点赋值为交换之后的第二个节点,也就是为下一次的交换做准备!

转载于:https://my.oschina.net/u/2822116/blog/805151

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值