首页 > 代码库 > [LeetCode]Swap Nodes in Pairs
[LeetCode]Swap Nodes in Pairs
题目:给定一个单链表,要求对链表每两两节点进行交换,例子: 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; } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。