zoukankan      html  css  js  c++  java
  • 链表翻转

    要求用尽可能快的方式实现链表的翻转操作。

    这个我们须要用两个指针。一个指向当前的节点,一个指向当前节点的前一个节点,每一次使当前节点的指向前一个节点来实现两个节点之间的翻转,然后顺次再移动实现循环。

    代码也非常easy,例如以下所看到的:

    #include <iostream>
    using namespace std;
    
    struct Node
    {
    	int key;
    	Node* next;
    };
    Node* createList(int arr[],int nLength);
    Node* reverseList(Node* head);
    void printList(Node* head);
    void clearList(Node* head);
    
    void main()
    {
    	int arr[] = {1,3,5,7,9};
    	int nLength = sizeof(arr)/sizeof(arr[0]);
    	Node* head = createList(arr,nLength);
    	printList(head);
    	head = reverseList(head);
    	printList(head);
    	clearList(head);
    }
    
    Node* createList(int arr[],int nLength)
    {
    	Node* head = new Node;
    	head->key = arr[0];
    	head->next = NULL;
    	Node *p = head;
    	for(int i=1;i<nLength;i++)
    	{
    		Node* ptr = new Node;
    		ptr->key = arr[i];
    		ptr->next = NULL;
    		p->next = ptr;
    		p = p->next;
    	}
    	return head;
    }
    
    Node* reverseList(Node* head)
    {
    	Node* preNode = NULL;
    	Node* pNode = head;
    	while( pNode != NULL )
    	{
    		Node* pNext = pNode->next;
    		pNode->next = preNode;
    		preNode = pNode;
    		pNode = pNext;
    
    	}
    	return preNode;
    }
    
    void printList(Node* head)
    {
    	Node* p = head;
    	while( p!= NULL )
    	{
    		cout<<p->key<<endl;
    		p=p->next;
    	}
    }
    
    void clearList(Node* head)
    {
    	Node* p = head;
    	Node* ptr;
    	while( p!= NULL )
    	{
    		ptr = p->next;
    		delete p;
    		p = ptr;
    	}
    }


  • 相关阅读:
    内存队列使用Channels
    笔记20210101mongodb
    管道式的开发模式
    企业级应用架构设计
    再入历史旧坑
    路径问题 再次记录
    mongdb驱动的问题
    使用Bumblebee记录
    我和小兔子不得不说的消息v2
    流程设计器jQuery + svg/vml(Demo7
  • 原文地址:https://www.cnblogs.com/jzssuanfa/p/7230460.html
Copyright © 2011-2022 走看看