leetcode------Swap Nodes in Pairs

本文详细介绍了链表两节点交换算法的实现过程,包括关键步骤和代码解析,通过实例展示如何仅使用常量空间交换相邻节点。
标题:Swap Nodes in Pairs
通过率:32.5
难度:中等

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-》4

再操作3,4交换后要将2指向4,不能再指向3了,另外,再第一次交换的时候要把链表的入口换成2,具体细节操作见代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode swapPairs(ListNode head) {
14         if(head==null||head.next==null)return head;
15         ListNode res=head;
16         ListNode first=head,second=head.next,pre=null;
17         int i=0;
18         ListNode tmp=new ListNode(-1);
19         while(second!=null){
20             tmp.next=second.next;
21             second.next=first;
22             first.next=tmp.next;
23             if(i==0)res=second;
24             if(pre!=null)pre.next=second;
25             pre=first;
26             first=first.next;
27             if(first==null)break;
28             second=first.next;
29             i=1;
30             
31         }
32         return res;
33     }
34 }

 

转载于:https://www.cnblogs.com/pkuYang/p/4333918.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值