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

    Subscribe to see which companies asked this question

    /**
     * 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) {
            if (NULL == head || NULL == head->next) {
                return head;
            }
            //模拟头结点,方便计算
            ListNode fake(0);
            ListNode* node = &fake;
            node->next = head;
            //从头结点开始进行翻转
            while (node && node->next) {
                node->next =  swap(node->next);
                node = node->next->next;
            }
            return fake.next;
        }
        //返回翻转之后的头结点
        ListNode* swap(ListNode* p) {
            ListNode* q = p->next;
            if (NULL == q) {
                return p;
            }
            ListNode* tmp = q->next;
            q->next = p;
            p->next = tmp;
            return q;
        }
    
    };
  • 相关阅读:
    JAVA日常之三
    java将字符串存入oracle的Blob中
    java连接oracle数据库
    JAVA日常之二
    JAVA日常之一
    linux日常命令之三
    linux日常命令之二
    linux日常命令之一
    Python之路【第四十篇】:django日更
    Python之路【第三十九篇】:django日更
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5119747.html
Copyright © 2011-2022 走看看