12440 - Tsai DS 20191017 Swap   

Description

Please read the following code, and complete the TODO part.

#include<iostream>
#include<string>
using namespace std;
 
class Node{
    private:
        char c;
        Node* next;
    public:
        Node(char c):c(c),next(0){}
        void setNext(Node* next){
            this->next=next;
        }
        Node* getNext(){
            return this->next;
        }
        char getChar(){
            return this->c;
        }
};
 
class LinkedList{
    private:
        Node* firstNode;
        Node* lastNode;
    public:
        LinkedList():firstNode(0),lastNode(0){}
        LinkedList(Node* node):firstNode(node),lastNode(node){}
        void push_back(Node* node){
             // TODO
        }
        void printAll(){
            // Printout all the elements in the linked list
            Node* currentNode=firstNode;
            while(currentNode!=0){
                cout<<currentNode->getChar();
                currentNode=currentNode->getNext();
            }
        }
        void swap(int index){
            // TODO
        }
};


 
int main(){
    string element;
    LinkedList l = LinkedList();
 
    getline(cin,element); //將輸入字串讀入string element
 
    for(int i=0;i<element.length();i++){
        l.push_back(new Node(element[i]));
    }
 
    // Get the swap index
    int index;
    cin>>index;
 
    l.swap(index);
    l.printAll();
    return 0;
}

First, you read in a string and use it to build a linked-list by performing push_back(Node* node) on every element

Each node of the linked-list stores one char from string sequentially.

For example, if the string has "abc", three characters, then

     node 1 : a , next=node2

     node 2 : b , next=node3

     node 3 : c , next=null

Second, you should implement swap(int index).

The function swap is to change the order of the node of the index and the node of index+1

For example, if we swap(2) in the above linked-list, it would become :

    node 1 : a , next=node3

    node 3 : c , next=node2

    node 2 : b , next=null

You should note that the index starts from "1", and you cannot modify any part except the TODO part.

 

 

 

 

Input

The first line of input data is string

The second line is swap index

<NOTE>

If the index is the tail of linked list, no change.

Output

Printout the linked list after swap

Sample Input  Download

Sample Output  Download

Tags

12440



Discuss