• Swap Nodes in Pairs——LeetCode


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

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

    Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

    题目大意:给定一个单链表,交换每两个元素。

    解题思路:采用头插法重新构建这个链表,每插入两个就把头指针移动到最后,再插入新的节点。

    Talk is cheap>>

        public ListNode swapPairs(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode res = new ListNode(0);
            res = head.next;
            ListNode cur = new ListNode(0);
            ListNode tmp = head;
            ListNode st = head;
            int cnt = 1;
            while (cur != null && st != null) {
                tmp = st.next;
                st.next = cur.next;
                cur.next = st;
                st = tmp;
                if (cnt == 2) {
                    cnt = 0;
                    cur = cur.next.next;
                }
                cnt++;
            }
            return res;
        }
  • 相关阅读:
    redis中文API
    基于redis的分布式锁
    redis安装使用配置
    windows常用命令
    curl命令详解
    linux远程连接
    memcache在大型网站的应用策略
    缓存使用的一些注意事项
    记录memcache分布式策略及算法
    U盘安装Centos7.0图解
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4447867.html
Copyright © 2020-2023  润新知