复习算法第二天,链表在区间内反转

414 阅读1分钟

个人觉得,最主要的是。储存上下一个节点,在反转后更改一下前后节点的指向

#include<stdio.h>
#include<stdlib.h>
int num;
struct stu
{
	int num;
	struct stu *next;
};
stu* initList()
{
	struct stu *head=(struct stu *)malloc(sizeof(struct stu));
	head->num = 0;
	head->next=NULL;//有头结点,头结点为空d
	return head;
}
void printList(struct stu *head)
{
	struct stu *p = head;
	while(p->next!=NULL)
	{
		printf("%d",p->next->num);
		p=p->next;
	}
	printf("\n"); 
}
void createList(struct stu *head,int n)
{
	struct stu *p1 = head,*p2;
	for(int i=0;i<n;i++)
	{
		p2=(struct stu *)malloc(sizeof(struct stu));
		p2->num = i+1;
		
		p1->next=p2;   
		p2->next=NULL;
		p1=p2;
	}
}
stu* reverseList(struct stu *head)
{
	struct stu *p,*q = NULL,*m=head,*n=head->next;
	while(head != NULL){
		p = head->next;
		head->next = q;
		q = head;
		head = p;
	}
	m->next = q;
	n->next = NULL;
	return m;
}
void reverseListBetween(struct stu *head,int m,int n)
{
	if(m==n || n<m||n-m > num|| n > num || m> num){
		printf("输入有误,请从新执行\n");
		exit(0);
	}
		
	
	int listLen = n-m+1;
	if(listLen == num){
		head = reverseList(head);
		return;
	}
		
	struct stu *p = head,*q = NULL,*front,*begin,*p2;
	while(p && m--){
		front = p;
		p = p->next;
	}
	begin = p;
	while(head && listLen--){
		p2 = p->next;
		p->next = q;
		q =p;
		p = p2;
	}
//	printf("%d",p2->num); 
	begin->next = p2;
	front->next = q;
}
int main()
{
	scanf("%d",&num);
	struct stu *head = initList();
	createList(head,num);
	printList(head);
//	head = reverseList(head);
//	printList(head);
	reverseListBetween(head,2,6);
	printList(head);
	return 0;
 }