迭代反转链表
通过定义三个指针,从头到尾依次改变链表的指向。
link *iteration_reverse(link *head){
if(head == NULL || head->next == NULL) //链表为空或者只有头结点
return head;
link *beg = NULL; //指向当前结点的上一个结点
link *mid = head; //指向当前结点
link *end = head->next; //指向当前结点的下一个结点
while(1){
mid->next = beg; //改变指向
if(end == NULL) //判断链表是否为空
break;
beg = mid; //后移结点
mid = end;
end = end->next;
}
head = mid; //改变头结点
return head;
}
递归反转链表
使用递归从链表结尾结点开始,依次向前编译,编译过程中依次改变结点的指向。
link *recursive_reverse(link *head){
if(head == NULL || head->next == NULL) //链表为空或者只有头结点
return head;
link *new_head = recursive_reverse(head->next);//递归编译链表
head->next->next = head; //改变结点指向
head->next = NULL;
//new_head一直都是最后的结点
return new_head;
}
头插法反转链表
通过建立一个新的链表,从旧链表的头部开始,依次取出结点,然后把结点插入到新的链表中。
link *head_reverse(link *head){
if(head == NULL || head->next == NULL) //链表为空或者只有头结点
return head;
link *new_head = NULL;
link *temp = NULL;
while(head != NULL){
temp = head; //取出旧链表头结点
head = head->next; //取出头结点,头结点后移
temp-next = new_head; //把结点插入新链表
new_head = temp; //把头结点改成新插入的结点
}
return new_head
}
就地逆置法反转链表
就地逆置法和头插法的实现思想类似,唯一的区别在于,头插法是通过建立一个新链表实现的,而就地逆置法则是通过借助两个指针,直接对原链表做修改,从而实现将原链表反转。
link *local_reverse(link *head){
if(head == NULL || head->next == NULL) //链表为空或者只有头结点
return head;
link *beg = head;
link *end = head->next;
while(end != NULL){
beg->next = end->next; //取出结点
end->next = head; //改变指向
head = end; //改变头结点
end = beg->next; //end指向待取出的结点
}
return head;
}
这只是本人的学习笔记
原文请移步:http://c.biancheng.net/view/8105.html