zoukankan      html  css  js  c++  java
  • 7两两交换链表中的节点(24)

    作者: Turbo时间限制: 1S章节: DS:数组和链表

    晚于: 2020-07-08 12:00:00后提交分数乘系数50%

    截止日期: 2020-07-15 12:00:00

    问题描述 :

    给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

    你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    可使用以下代码,完成其中的swapPairs函数,其中形参head指向无头结点单链表,返回结果链表的头指针。

    输入说明 :

    首先输入链表长度len,然后输入len个整数,以空格分隔。

    输出说明 :

    输出格式见范例

    输入范例 :

    4
    1 2 3 4

    输出范例:

    head-->2-->1-->4-->3-->tail
    #include<iostream>
    #include<vector>
    using namespace std;
    
    struct ListNode
    {
        int val;
        ListNode *next;
        ListNode() : val(0), next(NULL) {}
        ListNode(int x) : val(x), next(NULL) {}
        ListNode(int x, ListNode *next) : val(x), next(next) {}
    };
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) 
        {
            if(head==NULL||head->next==NULL)
                return head;
            ListNode *first=head;
            ListNode *second=head->next;
            head->next=swapPairs(second->next);
            second->next=first;
            return second;  
        }
    };
    ListNode *createByTail()
    {
        ListNode *head;
        ListNode *p1,*p2;
        int n=0,num;
        int len;
        cin>>len;
        head=NULL;
        while(n<len && cin>>num)
        {
            p1=new ListNode(num);
            n=n+1;
            if(n==1)
                head=p1;
            else
                p2->next=p1;
            p2=p1;
        }
        return head;
    }
    void  displayLink(ListNode *head)
    {
        ListNode *p;
        p=head;
        cout<<"head-->";
        while(p!= NULL)
        {
            cout<<p->val<<"-->";
            p=p->next;
        }
        cout<<"tail
    ";
    }
    int main()
    {
        ListNode* head = createByTail();
        head=Solution().swapPairs(head);
        displayLink(head);
        return 0;
    }
  • 相关阅读:
    Beginning Math and Physics For Game Programmers (Wendy Stahler 著)
    The Best Books on Game Dev
    Vector Math for 3D Computer Graphics (Bradley Kjell 著)
    2019年1月
    2018年12月
    Flocks,Herds and Schools: A Distributed Behavioral Model
    2018年11月
    2018年10月
    Tomcat基本
    对比Python中_,__,xx__xx
  • 原文地址:https://www.cnblogs.com/zmmm/p/13616702.html
Copyright © 2011-2022 走看看