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;
    }
    
    
    放弃很容易,但是坚持真的很酷,静享此刻,强风吹拂
  • 相关阅读:
    Tomcat造成404
    ajax缺少@ResponseBody注解前台404,业务可以运行
    几种常见的Runtime Exception
    SQL注入通俗讲解
    MYSQL数据库导入大数据量sql文件失败的解决方案
    css选择器
    http端口
    基础算法之最大子列求和问题
    基础算法之链表逆序
    Prolog&Epilog
  • 原文地址:https://www.cnblogs.com/joker8/p/15074292.html
Copyright © 2011-2022 走看看