美文网首页
Leetcode系列之链表(12)

Leetcode系列之链表(12)

作者: FisherTige_f2ef | 来源:发表于2019-10-28 23:25 被阅读0次

    题目:

    将给定的链表中每两个相邻的节点交换一次,返回链表的头指针

    例如,

    给出1->2->3->4,你应该返回链表2->1->4->3。

    你给出的算法只能使用常量级的空间。你不能修改列表中的值,只能修改节点本身。

    思路:

    1.普通的元素交换

    2.应当考虑题目的变形,或者与其他知识点的叠加

    代码:

    /**

    * Definition for singly-linked list.

    * public class ListNode {

    *    int val;

    *    ListNode next;

    *    ListNode(int x) {

    *        val = x;

    *        next = null;

    *    }

    * }

    */

    public class Solution {

        public ListNode swapPairs(ListNode head) {

            ListNode dump = new ListNode(0);

            dump.next = head;

            head = dump;

            while(head.next != null && head.next.next != null){

                ListNode n1 = head.next;

                ListNode n2 = head.next.next;

                head.next = n2;

                n1.next = n2.next;

                n2.next = n1;

                head = n1;

            }

            return dump.next;

        }

    }

    相关文章

      网友评论

          本文标题:Leetcode系列之链表(12)

          本文链接:https://www.haomeiwen.com/subject/naovvctx.html