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;
    }
    
    
    放弃很容易,但是坚持真的很酷,静享此刻,强风吹拂
  • 相关阅读:
    FPGA 设计怎样进行面积优化(逻辑资源占用量优化)
    实现文件下载的java代码
    java推断字符串是否为乱码
    cocos2dx 制作单机麻将(二)
    CPU 风扇清理灰尘加油全过程图解
    初识 Cloudera Impala
    怎样设计接口?
    Android ViewPager使用具体解释
    php反射类 ReflectionClass
    memwatch的使用
  • 原文地址:https://www.cnblogs.com/joker8/p/15074292.html
Copyright © 2011-2022 走看看