递归1——单链表的就地逆置(C)

递归1——单链表的就地逆置(C)_第1张图片

 递归1——单链表的就地逆置(C)_第2张图片

 

#include
#include
#include
typedef struct NODE {
	int n;
	struct NODE* next;
}NODE;
void Create(NODE* head, int n) {//尾插法创建单链表 
	NODE* q = head;
	for (; n > 0; n--) {
		NODE* p = (NODE*)malloc(sizeof(NODE));
		if (p) {
			char s[20];
			fgets(s, 10, stdin);
			p->n = atoi(s);
			q->next = p;
			q = p;
		}
	}
	q->next = NULL;
}
void Output(NODE* head) {//单链表的遍历 
	NODE* p = head->next;
	while (p) {
		printf("%d ", p->n);
		p = p->next;
	}
}
int Recursion(NODE* head, NODE* prior, NODE* now) {//单链表的反转 
	if (now->next != NULL)
		Recursion(head, prior->next, now->next);
	//下面用到了static,意思就一个,就是只执行1次 
	static int flag = 1;
	if ((flag == 1) && (now->next == NULL)) {
		head->next = now;
		flag = 0;
	}
	now->next = prior;
	prior->next = NULL;
	return 0;
}
int main()
{
	//首先,定义n,记录结点个数 
	char s[8];
	fgets(s, 5, stdin);
	int n = atoi(s);
	//然后,向n个结点中,存放数据 
	NODE* head = (NODE*)malloc(sizeof(NODE));
	if (head != NULL) {
		head->n = 0;
		Create(head, n);
	}
	//接着,反转单链表 
	NODE* prior = head->next;
	NODE* now = head->next->next;
	Recursion(head, prior, now);
	//最后,遍历单链表 
	Output(head);
}

 

你可能感兴趣的:(链表,C,数据结构,链表,c语言)