[LeetCode]24. Swap Nodes in Pairs

来源:互联网 发布:数据安全 国家安全法 编辑:程序博客网 时间:2024/05/29 02:03

https://leetcode.com/problems/swap-nodes-in-pairs/

链表可拆解问题依然两解,链表问题常要新加一个头结点



递归

/** * 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 next = swapPairs(head.next.next);        ListNode res = head.next;        res.next = head;        head.next = next;        return res;    }}



非递归

/** * 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) {        ListNode pre = new ListNode(0);        pre.next = head;        ListNode cur = pre;        while (cur.next != null && cur.next.next != null) {            ListNode first = cur.next;            ListNode second = cur.next.next;            first.next = second.next;            second.next = first;            cur.next = second;            cur = cur.next.next;        }        return pre.next;    }}


0 0
原创粉丝点击