zoukankan      html  css  js  c++  java
  • 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.

    交换相邻的两个结点,若只有奇数个结点,则最后一个结点不做改变

    个人思路:

    1,从链表头部开始遍历,分别用current指针记录当前结点,next指针记录下一个结点,pre指针记录前一个结点,每次循环都是把next指针指向的结点插入到pre指针之后,然后重新设置一下这3个指针,直到遍历结束

    2,注意一下结束条件即可

    代码:

     1 #include <stddef.h>
     2 
     3 struct ListNode
     4 {
     5     int val;
     6     ListNode *next;
     7     ListNode(int x) : val(x), next(NULL) {}
     8 };
     9 
    10 class Solution {
    11 public:
    12     ListNode *swapPairs(ListNode *head) {
    13         if (!head || !head->next)
    14         {
    15             return head;
    16         }
    17 
    18         ListNode dummy(-1);
    19         dummy.next = head;
    20         ListNode *pre = &dummy;
    21         ListNode *current = dummy.next;
    22         ListNode *next = NULL;
    23 
    24         while (current && current->next)
    25         {
    26             next = current->next;
    27 
    28             current->next = next->next;
    29             next->next = current;
    30             pre->next = next;
    31 
    32             pre = current;
    33             current = current->next;
    34         }
    35 
    36         return dummy.next;
    37     }
    38 };
    View Code

    网上基本是这个思路

  • 相关阅读:
    CA证书申请、认证原理
    流量异常监控
    排查和处理一台被攻击的linux系统及其事后分析
    day39---mysql基础三
    一次专利讲座的笔记
    HBase MVCC 代码阅读(一)
    [翻译]HBase 中的 ACID
    [翻译]HBase 的 MVCC 和内建的原子操作
    HBase Maven 工程模块梳理
    关于 MVCC 的基础
  • 原文地址:https://www.cnblogs.com/laihaiteng/p/3957596.html
Copyright © 2011-2022 走看看