LeetCode实战:两两交换链表中的节点

2019-04-18  本文已影响0人  老马的程序人生

题目英文

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

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.


题目中文

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.


算法实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
 
public class Solution
{
    public ListNode SwapPairs(ListNode head)
    {
        if (head == null || head.next == null)
            return head;

        head = Swap(head);
        
        ListNode temp = head.next;
        
        while (temp != null && temp.next != null)
        {
            temp.next = Swap(temp.next);
            if (temp.next != null)
            {
                temp = temp.next.next;
            }
        }
        return head;
    }

    public ListNode Swap(ListNode node)
    {
        if (node == null || node.next == null)
            return node;

        ListNode t = node.next;
        node.next = t.next;
        t.next = node;
        return t;
    }
}

实验结果

提交记录

相关图文

上一篇 下一篇

猜你喜欢

热点阅读