【Leetcode】24. Swap Nodes in Pairs

来源:互联网 发布:mac网络加速器 编辑:程序博客网 时间:2024/06/18 14:57

方法一:

思路:

(1)p1指向空,p2指向头节点,p3指向头结点的下一节点。

(2)遍历整个链表直到p3为空。

(3)每次遍历,将p2的next指向p3的next,再将p3的next指向p2,若p1为空,则头指针指向p3,否则将p1的next指向p3。

(4)每次遍历后,将p1指向p2,若p1为空,直接返回head,否则,将p2指向p1的next,若p2为空,直接返回head,否则,将p3指向p2的next,继续下一次遍历。

/** * 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 p1 = null, p2 = head, p3 = head.next;        while (p3 != null) {            p2.next = p3.next;            p3.next = p2;            if (p1 == null)                 head = p3;            else                p1.next = p3;            p1 = p2;            if (p1 == null)                return head;            else {                p2 = p1.next;                if (p2 != null)                    p3 = p2.next;                else                    return head;            }        }        return head;    }}

Runtime:5ms

方法二:递归

思路:

(1)交换前2个节点。

(2)交换除去前2个节点外的后续节点组成的链表,返回新的头结点p。

(3)将交换后的前两个节点接到p链表上,最终链表的头结点为p2。

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

Runtime:4ms

1 0
原创粉丝点击