zoukankan      html  css  js  c++  java
  • leetcode: Swap Nodes in Pairs

    http://oj.leetcode.com/problems/swap-nodes-in-pairs/

    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.

    思路

    每次读两个节点插入新链表,因为是指针操作,不占用额外空间。最后需要把tail指针的next设为NULL。例如链表为p1->p2->p3->p4的情况,如果最后不修改p3->next,那么就会出现一个环:p2->p1->p4->p3->p4->...

     1 class Solution {
     2 public:
     3     void insertTwoNodes(ListNode *p1, ListNode *p2, ListNode *&head, ListNode *&tail) {
     4         if (NULL == head) {
     5             head = tail = p2;
     6         }
     7         else {
     8             if (p2 != NULL) {
     9                 tail->next = p2;
    10                 tail = p2;
    11             }
    12         }
    13         
    14         if (NULL == head) {
    15             head = tail = p1;
    16         }
    17         else {
    18             tail->next = p1;
    19             tail = p1;
    20         }
    21     }
    22     
    23     ListNode *swapPairs(ListNode *head) {
    24         ListNode *swapped_head = NULL, *swapped_tail = NULL;
    25         
    26         while (head != NULL) {
    27             ListNode *p1 = NULL, *p2 = NULL;
    28             
    29             p1 = head;
    30             head = head->next;
    31             
    32             if (head != NULL) {
    33                 p2 = head;
    34                 head = head->next;
    35             }
    36             
    37             insertTwoNodes(p1, p2, swapped_head, swapped_tail);
    38         }
    39         
    40         if (NULL != swapped_tail) {
    41             swapped_tail->next = NULL;
    42         }
    43         
    44         return swapped_head;
    45     }
    46 };
  • 相关阅读:
    Jenkins 插件管理
    持续集成 目录
    gitlab 目录
    jenkins 目录
    POJ 2828
    POJ 2782
    POJ 2725
    POJ 2769
    POJ 2739
    POJ 2707
  • 原文地址:https://www.cnblogs.com/panda_lin/p/swap_nodes_in_pairs.html
Copyright © 2011-2022 走看看