• 链表反转 C++


    ListNode* reverse1(ListNode* pHead)
    {
    	if(pHead == NULL)		
    		return NULL;
    	ListNode * p1 = NULL;
    	ListNode * p2 = pHead;
    	ListNode * p3 = pHead->next;
    	while(p3!=NULL)
    	{
    		p2->next = p1;
    		p1 = p2;
    		p2 = p3;
    		p3 = p3->next;
    	}
    	p2->next = p1;
    	pHead = p2;
    	return pHead;
    }

    完整类代码

    <pre name="code" class="cpp">struct ListNode
    {
    	int data;
    	ListNode * next;
    };
    
    class ReverseLink
    {
    public:
    	ListNode * pHead;
    	void init()
    	{		
    		pHead=NULL;
    		for(int i=0; i<10; i++)
    		{
    			insert(i);
    		}
    	}
    	//插入链表最后
    	void insert(int data)
    	{
    		ListNode * p = new ListNode();
    		p->data = data;
    		p->next = NULL;
    
    		if(pHead==NULL)
    		{
    			pHead = p;
    			return;
    		}
    		
    		ListNode * cur = pHead;
    		while (cur->next!=NULL)
    		{
    			cur = cur->next;
    		}		
    		cur->next = p;
    	}
    	void print()
    	{
    		ListNode * p = pHead;
    		while (p!=NULL)
    		{
    			cout<<p->data<<endl;
    			p = p->next;
    		}
    	}
    	//反转
    	void reverse()
    	{
    		if(pHead->next == NULL)		
    			return;		
    		ListNode * p1 = NULL;
    		ListNode * p2 = pHead;
    		ListNode * p3 = pHead->next;
    		while(p3!=NULL)
    		{
    			p2->next = p1;
    			p1 = p2;
    			p2 = p3;
    			p3 = p3->next;
    		}
    		p2->next = p1;
    		pHead = p2;
    	}
    };
    
    int main()
    {
        ReverseLink rl;
    	rl.init();
    	rl.print();
    	cout<<"reverse"<<endl;
    	rl.reverse();
    	rl.print();
    	return 0;
    }
    


    
    
    
    
  • 相关阅读:
    输入框组
    下拉菜单
    地毯文(立足根本的基础细节篇)
    按钮组 button group
    offices web apps server2013 部署
    appium学习
    python练习
    Jmeter分布式测试
    centos安装远程桌面
    进程与线程
  • 原文地址:https://www.cnblogs.com/yan456jie/p/5369398.html
Copyright © 2020-2023  润新知