首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 其他相关 >

软件工程师面试100题(算法)之反转单链表(含单向链表的创建和打印)

2012-09-15 
程序员面试100题(算法)之反转单链表(含单向链表的创建和打印)// 程序员面试100题(算法)之反转单链表#inclu

程序员面试100题(算法)之反转单链表(含单向链表的创建和打印)

// 程序员面试100题(算法)之反转单链表#include "stdafx.h"#include <iostream>using namespace std;struct LinkNode{int value;LinkNode *next;};LinkNode *CreateLink(LinkNode *headNode, int &length){int data = 0;LinkNode *previous, *post;if(NULL == headNode){cin >> data;if(-1 == data)return NULL;headNode = (LinkNode*)malloc(sizeof(LinkNode));if(headNode){headNode->value = data;headNode->next = NULL;length++;}else{cout << "No space" <<endl;}}previous = post = headNode;cin >> data;while(data != -1){post = (LinkNode*)malloc(sizeof(LinkNode));if(post){post->value = data;post->next = NULL;previous->next = post;previous = post;length++;}else{cout << "No space" << endl;}cin >> data;}return headNode;}void PrintLink(LinkNode *headNode){if(headNode == NULL){cout << "Linklist is empty" <<endl;return;}LinkNode *p = headNode;while(p){cout << p->value << "  ";p = p->next;}cout << endl;}LinkNode *ReverseLink(LinkNode *headNode){if(NULL == headNode)return NULL;if(NULL == headNode->next)return headNode;LinkNode *previous, *post, *r;previous = headNode;post = headNode->next;while(post != NULL){r = post->next;post->next = previous;previous = post;post = r;}headNode->next = NULL;return previous;}int _tmain(int argc, _TCHAR* argv[]){int length = 0;LinkNode *headNode = NULL;cout << "Create a linklist(end up with -1)" <<endl;headNode = CreateLink(headNode, length);PrintLink(headNode);headNode = ReverseLink(headNode);PrintLink(headNode);return 0;
}

热点排行