链表分为两种,一种有头指针,头指针没有值只存储地址,一种是不带头指针的,第一个节点即为实际第一点,有值。
下面的代码为带头指针的链表反转。
#include <assert.h>
#include <stdio.h>
#include <iostream>
using namespace std;
typedef struct node
{
int data;
node* next;
};
//建立链表
node* create_link( int* array ,int length)
{
node* phead = new node(); //带有表头的链表,表头中不存储任何元素
node* preNode = phead;
for( int i=0; i<length; i++ )
{
struct node * pNode = new node();
pNode->data = array[i];
pNode->next = NULL;
preNode->next = pNode;
preNode = pNode;
}
return phead;
}
//输出链表
void out_link( node* phead )
{
if( phead == NULL )
return;
struct node * pNode = phead->next;
while( pNode )
{
cout <<pNode->data;
pNode = pNode->next;
}
cout << endl;
}
node* reverse_linktable(node* phead)
{
assert(NULL!=phead&&NULL!=phead->next);
node *pre,*cur,*next;
cur=phead->next;
pre=NULL;//开始时pre为空
while(cur!=NULL)
{
next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
phead->next=pre;
return phead;
}
void test()
{
int array[]={5,2,4,7,8,1,3,9,6,0};
node *phead=create_link(array,10);
cout<<"反转前链表:";
out_link(phead);
cout<<"反转后链表:";
node *pphead=reverse_linktable(phead);
out_link(pphead);
}
int main()
{
test();
system("pause");
return 0;
}