zoukankan      html  css  js  c++  java
  • 单向链表反转

    1. 单向链表反转
    #include <iostream>
    #include <string>
    #include <sstream>
    
    using std::cout;
    using std::cin;
    using std::endl;
    using std::string;
    using std::ostringstream;
    
    namespace {
    
    struct ListNode {
    	ListNode(int number, const string message)
    		:number_(number), message_(message)
    	{}
    	int number_;
    	string message_;
    	ListNode* next_;
    };
    
    void printList(ListNode* head)
    {
    	ostringstream oss;
    	for (ListNode* temp = head; temp; temp = temp->next_) {
    		oss << "index:" << temp->number_ << " message:" << temp->message_ << '
    ';
    	}
    	cout << oss.str() << endl;
    }
    
    // return list head
    ListNode* createList(size_t count)
    {
    	string message;
    	std::allocator<ListNode> alloc;
    	ListNode *head, *current, *temp;
    
    	for (size_t i = 0; i < count; ++i) {
    		temp = alloc.allocate(sizeof(*temp));
    		cin >> message;
    		alloc.construct(temp, i, message);
    		if (i == 0) {
    			head = current = temp;
    		} else {
    			current->next_ = temp;
    			current = temp;
    		}
    	}
    
    	return head;
    }
    
    // return the new head
    ListNode* reverseList(ListNode* head)
    {
    	ListNode *current, *next, *prev = nullptr;
    
    	for (current = head; current; current = next) {
    		next = current->next_;
    		current->next_ = prev;
    		prev = current;
    		if (next == nullptr)
    			break;
    	}
    
    	return current;
    }
    
    void listTest(size_t n)
    {
    	ListNode* head = createList(n);
    	if (head)
    		printList(head);
    	ListNode* rhead = reverseList(head);
    	if (rhead)
    		printList(rhead);
    }
    
    } // namespace
    
    int main(void)
    {
    	listTest(10);
    	return 0;
    }
    
    
    放弃很容易,但是坚持真的很酷,静享此刻,强风吹拂
  • 相关阅读:
    几种开源工作流引擎的简单比较(转)
    ExecuteScalar
    机房重构---我们“重构”出了什么?
    薏米红豆粥功效及做法介绍
    Mean Shift具体介绍
    linux fork函数浅析
    html的下拉框的几个基本使用方法
    Readprocessmemory使用方法
    配置Log4j(非常具体)
    【Linux】linux经常使用基本命令
  • 原文地址:https://www.cnblogs.com/joker8/p/15074292.html
Copyright © 2011-2022 走看看