[LeetCode]Swap Nodes in Pairs

本文深入解析了链表操作中的一种特定算法——如何实现对链表每两两节点进行交换。通过引入四个关键指针:左边界、交换节点A、交换节点B和右边界,本文详细阐述了算法的实现过程,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:给定一个单链表,要求对链表每两两节点进行交换,例子: 1->2->3->4, 交换后 2->1->4->3.

算法:链表操作,设置4个指针

pre:左边界,维护交换后链表的结构

swapA:指向要交换的第一个节点

swapB:指向要交换的第二个节点

post:右边界,维护交换后链表的结构


链表:...->1->2->3->4

对应:pre  swapA  swapB  post

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode swapPairs(ListNode head) {
	        if (null == head) {
	        	return null;
	        }
	    	
	    	ListNode pre = head;
	        ListNode post = null;
	        ListNode swapA = head;
	        ListNode swapB = null;
	        while (null != pre) {
	        	if (head == pre) {
	        		// begin with the list head
	        		if (null != pre.next) {
	        			swapA = pre;
	        			swapB = swapA.next;
	        			post = swapB.next;
	        			
	        			// swap node pair
	        			swapA.next = post;
	        			swapB.next = swapA;
	        			head = swapB;
	        		} else {
	        			break;
	        		}
	        	} else {
//	        		pre = swapA;  // after swap
	        		if (null != pre.next) {
		        		swapA = pre.next;
		        		if (null != swapA.next) {
		        			swapB = swapA.next;
		        			post = swapB.next;
		        			
		        			// swap node pair
		        			pre.next = swapB;
		            		swapB.next = swapA;
		            		swapA.next = post;
		        		} else {
		        			break;  // last one node, don't swap
		        		}
		        	} else {
		        		break;  // end of the list
		        	}
	        	}
	        	
	        	pre = swapA;  // after swap
	        }
	        
	        return head;
	    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值