从头开始摘节点,依次连起来。
#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” 博客,转载请与作者联系!