【LeetCode每日一题】[中等]24. 两两交换链表中的节点

【LeetCode每日一题】[中等]24. 两两交换链表中的节点

24. 两两交换链表中的节点

题目来源
算法思想:链表

题目:
在这里插入图片描述
思路:

  1. 需要3个指针;
  2. 其中两个用来交换结点;如:[1,2]交换成[2,1],[3,4]交换成[4,3]
  3. 第三个用来连接结点,实现[2,1]与[3,4]的连接
    在这里插入图片描述

java代码

class Solution {
    
    
    public ListNode swapPairs(ListNode head) {
    
    
		ListNode first = new ListNode(0);//头结点,便于返回
		ListNode prior = new ListNode(0);//三个指针中的第三个,连接作用
		first.next = prior;
		prior.next = head;//连接结点位于交换结点的前面一个位置
		while (head != null && head.next != null) {
    
    
		//[head,p1]是要交换的节点,
		//p2因为java的关系,指针没法使用,要利用索引指向下一个结点
			ListNode p1 = head.next;//指向要交换的节点
			ListNode p2 = p1.next;//指向下一对交换结点的开始
			prior.next = p1;//连接结点prior指向p1
			head.next = p2;//进行交换[head,p1]
        	p1.next = head;
        	prior = head;//指针下移,prior指向下一个交换结点的前一个
        	head = p2;//head指向下一个交换结点的第一位
        	
		}
		return first.next.next;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39457586/article/details/109046709