单链表反转

单链表反转,可以用循环做,当然也可以递归

详见代码:

#include<stdio.h>
#include<stdlib.h>

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

/*
3 -> 1 -> 4 -> 6 -> 2			(1)
1 -> 3 -> 4 -> 6 -> 2			(2)
4 -> 1 -> 3 -> 6 -> 2			(3)
6 -> 4 -> 1 -> 3 -> 2			(4)
2 -> 6 -> 4 -> 1 -> 3			(5)

循环反转,即依次改动3个指针值,直到链表反转完成
比如,上面第(1)行到第(2)行,过程如下
head(原本指向3) 指向 1;
3(原本指向1) 指向 4;
1(原本指向4) 指向 3;
*/
void Rev_link(Node * & head){

	Node * _cur,* _next,*tmp;
	_cur = head;
	_next = _cur->next;
	tmp = _cur;
	while(_cur->next != NULL){
		head = _next;
		_cur->next = _next->next;
		_next->next = tmp;
		
		_next = _cur->next;
		tmp = head;
	}
}

Node * Tmd(Node * head,Node *pre){//头和前驱
	Node * p = head->next;	//保存头的下一个元素,用来递归
	head->next = pre;		//链表的反向,即 next 指针指向 其前驱
	if(p!=NULL)
		return Tmd(p,head);
	else 
		return head;
}

void put_link(Node * head){
	while(head!=NULL){
		printf("%d ",head->data);               
		head=head->next;
	}puts("");
}

int main(){
	int i,a[5]={2,6,4,1,3};
	Node * head = NULL;
	for(i=0;i<5;i++){
		Node * p=(Node *)malloc(sizeof(Node));
		p->data=a[i];
		p->next=head;
		head=p;
	}
	printf("*************原始链表*************\n");
	put_link(head);

	Rev_link(head);	//while循环反转
	printf("\n*************循环反转*************\n");
	put_link(head);

	head = Tmd(head,NULL);	//递归反转
	printf("\n*************递归反转*************\n");
	put_link(head);

	return 0;
}


你可能感兴趣的:(null)