码迷,mamicode.com
首页 > 其他好文 > 详细

链表的反转

时间:2016-05-13 04:47:49      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:链表的反转

从头开始摘节点,依次连起来。

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
 
struct Listnode
{
    int _value;
    Listnode* _next;
};
void Init(Listnode*& head)
{
    Listnode* cur =head;
    if(cur==NULL)
    {
        cur=(Listnode*)malloc(sizeof(Listnode));
        cur->_next=NULL;
        cur->_value=0;
    }
    head=cur;
}
 
void push(Listnode*& head,int value)
{
    Listnode* cur =head;
 
        while(cur->_next)
        {
            cur=cur->_next;
        }
        Listnode* tmp=NULL;
        tmp=(Listnode*)malloc(sizeof(Listnode));
        tmp->_next=NULL;
        tmp->_value=value;
        cur->_next=tmp;
     
         
 
}
void pop(Listnode* head)
{
    Listnode* cur=head;
    Listnode* prev=NULL;
    while(cur->_next!=NULL)
    {
        prev=cur;
        cur=cur->_next;
    }
    prev->_next=NULL;
    free(cur);
    cur=NULL;
}
void print(Listnode* head)
{
    Listnode* cur=head;
    while(cur)
    {
        printf("%d\n",cur->_value);
        cur=cur->_next;
    }
}
Listnode* reverse(Listnode* head)
{
	Listnode* newhead=NULL;
	if(head==NULL||head->_next==NULL)
	{
		return head;
	}
	while(head)
	{
		Listnode* tmp=head;
		head=head->_next;
		tmp->_next=newhead;
		newhead=tmp;
		
	}
	return newhead;
}

void test()
{
    Listnode* head=NULL;
    Init(head);
    push(head,1);
    push(head,2);
    push(head,3);
    /*pop(head);*/
     print(head);
    printf("逆转后\n");
	print(reverse(head));
   
 
}
int main()
{
    test();
    system("pause");
    return 0;
}

结果:技术分享

本文出自 “liveyoung” 博客,转载请与作者联系!

链表的反转

标签:链表的反转

原文地址:http://youngyoungla.blog.51cto.com/10697042/1772788

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!