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;
        }
    
    };
  • 相关阅读:
    hdu1754线段树入门
    hdu1247 字典树模板
    完全背包 poj 1384
    hdu 1541 树状数入门
    hdu 2665 划分树模板
    winhex分析磁盘目录结构(未完待续)
    取出表单中元素的js代码
    c语言检测cpu大小端模式
    firefox的cookie
    c移位实现求余
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5119747.html
Copyright © 2011-2022 走看看