码迷,mamicode.com
首页 > 其他好文 > 详细

单链表创建与反转

时间:2016-02-28 06:29:16      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

#include <iostream>
#include <fstream>

using namespace std;

struct LinkNode
{
    int data;
    LinkNode* next;
};

LinkNode* createLink(LinkNode* head)
{
    ifstream fin;
    fin.open("list.txt");

    if(!fin){
        cout << "open file failed......" << endl;
        return head;
    }
    LinkNode* tail = NULL;
    int data;
    while(fin>>data){
        LinkNode* node = new LinkNode();
        node->data = data;
        node->next = NULL;
        //cout << data << endl;
        if(head==NULL){
            head=node;
            tail=node;
        }
        else{
            tail->next = node;
            tail = node;
        }
    }
    return head;

}

LinkNode* reverseLink(LinkNode* head)
{
    LinkNode* node = head;
    LinkNode* reverseHead = NULL;
    LinkNode* pre = NULL;
    LinkNode* next = NULL;
    while(node!=NULL){
        next = node->next;
        if(next == NULL){
            reverseHead = node;
        }
        node->next = pre;
        pre = node;
        node = next;
    }
    return reverseHead;
}

void print(LinkNode* head)
{
    if(head == NULL){
        cout << "linknode is null" <<endl;
        return;
    }
    LinkNode* node = head;
    while(node!=NULL){
        cout << node->data <<endl;
        node = node->next;
    }

}

int main()
{
    LinkNode* head = NULL;
    head = createLink(head);
    print(head);
    head = reverseLink(head);
    print(head);
    return 0;
}

 

单链表创建与反转

标签:

原文地址:http://www.cnblogs.com/lifeinsmile/p/5223980.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!