九度 遍历链表

/*

 * c.cpp

 *

 *  Created on: 2013-10-7

 *      Author: wangzhu

 */



#include<cstdio>

#include<iostream>

using namespace std;

struct Node {

    int key;

    Node* next;

};

void addToTail(Node* root, int val) {

    Node* node = new Node;

    node->key = val;

    node->next = NULL;



    if (root->next == NULL) {

        root->next = node;

    } else {

        Node* tempNode = root->next;

        Node* tempPNode = root;

        while (tempNode->next != NULL) {

            if (tempNode->key > val) {

                Node* temp = tempPNode->next;

                node->next = temp;

                tempPNode->next = node;

                return;

            }

            tempNode = tempNode->next;

            tempPNode = tempPNode->next;

        }

        if (tempNode->key > val) {

            Node* temp = tempPNode->next;

            node->next = temp;

            tempPNode->next = node;

            return;

        }

        tempNode->next = node;

    }

}

void printTail(Node* node) {

    while (node->next != NULL) {

        printf("%d ", node->key);

        node = node->next;

    }

    printf("%d\n", node->key);

}

int main() {

    freopen("data.in", "r", stdin);

    int n,val;

    Node* root;

    while(~scanf("%d",&n)) {

        root = new Node;

        root->next = NULL;

        for(int i = 0;i < n;i++) {

            scanf("%d",&val);

            addToTail(root,val);

        }

        printTail(root->next);

    }

    return 0;

}

 

你可能感兴趣的:(遍历)