24. 兩兩交換鏈表中的節點
給定一個鏈表,兩兩交換其中相鄰的節點,并回傳交換后的鏈表,
你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換,
示例:
給定 1->2->3->4, 你應該回傳 2->1->4->3.
解題:
public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } class Solution { public ListNode swapPairs(ListNode head) { // 遞回 // if (head == null || head.next == null) { // return head; // } // ListNode next = head.next; // head.next = swapPairs(next.next); // next.next = head; // return next; // 非遞回 ListNode pre = new ListNode(0); pre.next = head; ListNode temp = pre; while(temp.next != null && temp.next.next != null) {// 1 ListNode start=tmp.next; // 2 ListNode end=tmp.next.next; // 0->2 tmp.next=end; // 1>3>4 start.next=end.next; // 2>1>3>4 end.next=start; // 1>3>4 tmp=start;
} return pre.next; // // 作者:guanpengchn // 鏈接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/solution/hua-jie-suan-fa-24-liang-liang-jiao-huan-lian-biao/ // 來源:力扣(LeetCode) // 著作權歸作者所有,商業轉載請聯系作者獲得授權,非商業轉載請注明出處, } public static void main(String[] args) { ListNode node1 = new ListNode(1); ListNode node2 = new ListNode(2); ListNode node3 = new ListNode(3); ListNode node4 = new ListNode(4); node1.next = node2; node2.next = node3; node3.next = node4; ListNode listNode = new Solution().swapPairs(node1); while (listNode!=null){ System.out.print(listNode.val+" -> "); listNode=listNode.next; } } }
參考:圖解演算法
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/162686.html
標籤:Java
上一篇:Java_圖片轉字符
下一篇:MQ系列(0)——MQ簡介
