国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

[LeetCode] Swap Nodes in Pairs

2019-11-15 01:16:09
字體:
供稿:網(wǎng)友
[LeetCode] Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

For example,Given1->2->3->4, you should return the list as2->1->4->3.

Your algorithm should use only constant space. You maynotmodify the values in the list, only nodes itself can be changed.

這道題難度不大。根據(jù)提供的example我們就可以看出這個swap是按照什么順序來的。就是相鄰的兩個交換,然后接著下面相鄰的兩個這樣。

那么只要確定head!=null和head.next!=null就可以成功交換值了。if statement這里主要就是判斷是否有null出現(xiàn)。

如果到了末尾出現(xiàn)了null的話,PRe/curr也只能變成null了。

理清了思路就很好寫了。

代碼如下。~

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode swapPairs(ListNode head) {        if(head==null||head.next==null){            return head;        }                ListNode curr=head.next;        ListNode pre=head;        while(pre!=null&&curr!=null){            int temp=curr.val;            curr.val=pre.val;            pre.val=temp;            if(curr.next==null){                curr=null;                pre=null;            }else{                pre=curr.next;                curr=curr.next.next;                           }        }        return head;    }}


上一篇:hello word

下一篇:[LeetCode] Isomorphic Strings

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 井陉县| 吉木乃县| 南昌县| 宣汉县| 林口县| 环江| 屏东县| 玛曲县| 南安市| 图们市| 汪清县| 六盘水市| 松江区| 肥乡县| 额济纳旗| 建昌县| 聂荣县| 轮台县| 迁西县| 会昌县| 岱山县| 潮安县| 安国市| 吕梁市| 连州市| 历史| 方城县| 昭苏县| 景宁| 富川| 板桥市| 隆安县| 会昌县| 蓝田县| 潍坊市| 区。| 循化| 五大连池市| 新余市| 双柏县| 肥乡县|