国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 榆林市| 措勤县| 金乡县| 九江市| 花莲县| 河南省| 定襄县| 旬阳县| 论坛| 青浦区| 龙川县| 永城市| 会同县| 奉节县| 苍山县| 阿拉善左旗| 苏州市| 秦安县| 武夷山市| 阿拉善右旗| 且末县| 荆门市| 东乡族自治县| 靖远县| 满城县| 佳木斯市| 清涧县| 雅江县| 庆阳市| 玉林市| 平远县| 河南省| 图们市| 沙河市| 嘉黎县| 安义县| 吉林省| 肥东县| 三河市| 左贡县| 沐川县|