zoukankan      html  css  js  c++  java
  • [Linked List]Swap Nodes in Pairs

    Total Accepted: 73777 Total Submissions: 219963 Difficulty: Medium

    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.

     
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            ListNode* first=head;
            ListNode* second = first ? first->next:NULL;
            ListNode* next=NULL,*pre=NULL;
            while(first && second){
                next = second->next;
                second->next = first;
                first->next = next;
                pre ? pre->next = second: head = second;//有前驱的话,前驱的下一几点指向交换后的两个节点的头,否则,为第一次交换,更新头结点.
                pre  = first;
                first=next;
                second = first ? first->next:NULL;
            }
            return head;
        }
    };
  • 相关阅读:
    架构阅读笔记9
    架构阅读笔记8
    架构阅读笔记7
    架构阅读笔记6
    架构阅读笔记5
    git安装使用详解
    mysql主从
    人定胜天
    jquery即点击改
    无限极分类/数组处理
  • 原文地址:https://www.cnblogs.com/zengzy/p/5041308.html
Copyright © 2011-2022 走看看