您的位置:首页 > 其它

链表相邻元素翻转,如a->b->c->d->e->f-g,翻转后变为:b->a->d->c->f->e->g

2011-10-26 19:39 357 查看
常见的三指针方法

struct node {
int data;
node * next;
};

node* inverseList(node *head){
if(head==NULL||head->next==NULL) return head;
node *pre = NULL;
node *cur = head;
node *next =NULL;

while(cur&&cur->next){
if(pre){
pre->next = cur->next;
}else{
head = cur->next;
}

pre = cur;
next = cur->next->next;
cur->next->next = cur;
cur->next = next;
cur = next;

}
return head;
}
node* createList(){
node* head=NULL;
node* cur=NULL;
node* pn;
for(int i=0;i<100;++i){
pn = new node;
pn->data = i;
if(cur==NULL)
{
head = pn;
cur = pn;
}else{
cur->next = pn;
cur = pn;
}
cur->next = NULL;
}
return head;
}
node* deleteList(node* head){
if(head==NULL) return NULL;
node * cur = head;
node * next = NULL;
while(cur){
next = cur->next;
delete cur;
cur = next;
}
return NULL;
}
void printList(node* head){
if(head){
printf("%d",head->data);
}
head = head->next;
while(head){
printf("->%d",head->data);
head = head->next;
}
printf("\r\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
node *head=createList();
printList(head);
head = inverseList(head);
printList(head);
deleteList(head);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  null struct