Leetcode 兩兩交換鍊錶中的節點

2022-07-24 21:00:25 字數 694 閱讀 2265

兩兩交換鍊錶中的節點

題意:給定乙個鍊錶,兩兩交換其中相鄰的節點,並返回交換後的鍊錶。

你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。

給定1->2->3->4, 你應該返回2->1->4->3.

題解:這個題建議自己畫個圖。。

主要步驟大概就以下三步。能想出來,這個題基本就解決了。

1、使新鍊錶節點的ans的下乙個節點變成head的下乙個節點。

2、使head節點的下乙個節點變成head的下下節點。

3、使ans下下節點變成head。

完成這三步再去做乙個更新,。ans當前節點更新到head的位置,head往下更新。

**:

1/**

2* definition for singly-linked list.

3* struct listnode

7* };8*/

9class

solution

25return ans->next;26}

27 };

leetcode演算法題 鍊錶 兩兩交換鍊錶中的節點

給定乙個鍊錶,兩兩交換其中相鄰的節點,並返回交換後的鍊錶。你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。package com.leetcode.鍊錶 author markuszhang vm args date create in 2020 2 2 15 23 public cl...

兩兩交換鍊錶中的節點 leetcode

leetcode位址 兩兩交換鍊錶中的節點 使用兩種方法,迭代和遞迴 這是使用的節點類 public class listnode listnode int val listnode int val,listnode next 判斷是否滿足條件,這裡的條件設定為鍊錶的個數是否為偶數,判斷方法為利用當...

LeetCode實戰 兩兩交換鍊錶中的節點

given a linked list,swap every two adjacent nodes and return its head.you maynotmodify the values in the list s nodes,only nodes itself may be changed...