复习算法第一题,链表倒序

296 阅读1分钟

仅仅实现,没有优化之类。

想想自己也是天天给别人讲链表的,自己现在却卡了一下。没脸了

倒序最主要的

  1. 先保存下一个节点的位置
  2. 改变这个节点的指向,并且用指针指着防止找不到
while(head != NULL){
		p = head->next;
		head->next = q;
		q= head;
		head = p;
	}
#include<stdio.h>
#include<stdlib.h>

struct stu {
	int num;
	struct stu *next;
};
int main(){
	int count,i;
	scanf("%d",&count);
	struct stu *head,*p,*q;
	head=(struct stu *)malloc(sizeof(struct stu));
	head->next=NULL;
	p=head;
	for(i=0;i<count;i++){
		// 创建并赋值 
		q = (struct stu *)malloc(sizeof(struct stu));
		scanf("%d",&q->num);
		// 指针移动 
		p->next = q; 
		q->next=NULL;
		p=p->next;
	}
	// 重新指向头 
	p=head;
	while(p->next!=NULL)
	{
		printf("%d",p->next->num);
		p=p->next;
	}
	printf("\n");
	q = NULL;
	// 开始倒序 
	while(head != NULL){
		p = head->next;
		head->next = q;
		q= head;
		head = p;
	}
	head = q;
	while(head->next!=NULL)
	{
		printf("%5d",head->num);
		head=head->next;
	}
}