链表翻转(面试题目 C语言实现)

题目:给出一个链表和一个数k,比如,链表为1→2→3→4→5→6,k=2,则翻转后2→1→6→5→4→3,若k=3,翻转后3→2→1→6→5→4,若k=4,翻转后4→3→2→1→6→5,用程序实现。

我的思路是:采用插入法翻转链表。

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

typedef struct node
{
	int data;
	struct node *next;
};

void CreateList(node *head,int length);
void PrintList(node *head);
void RotateList(node *head, int from, int to);
void ShiftList(node *head, int k, int n);

int main()
{
	int len,k;
	node * head = (node*)malloc(sizeof(node));
	printf("input the list length:\n");
	scanf_s("%d", &len);
	CreateList(head, len);
	PrintList(head);
	printf("input k:\n");
	scanf_s("%d", &k);
	ShiftList(head, k, len);
	PrintList(head);

	system("pause");
	return 0;
}

void CreateList(node *head,int len)
{
	node *p,*q;
	head->data = NULL;
	p = (node*)malloc(sizeof(node));
	p = head;
	for (int i = 0; i < len; i++)
	{
		q = (node*)malloc(sizeof(node));
		scanf_s("%d", &(q->data));
		q->next = NULL;
		p->next = q;
		p = p->next;
	}
}

void PrintList(node *head)
{
	node *temp = (node*)malloc(sizeof(node));
	temp = head;
	while (temp->next != NULL)
	{
		temp = temp->next;
		printf("%d  ", temp->data);
	}
	printf("\n");
}

void RotateList(node *head, int from, int to)
{
	node *p, *q, *tail;
	p = (node*)malloc(sizeof(node));
	p = head;
	for (int i = 1; i < from; i++)
	{
		p = p->next;
	}

	tail = (node*)malloc(sizeof(node));	
	tail = p;
	p = p->next;

	q = (node*)malloc(sizeof(node));
	for (int i = from; i < to; i++)
	{
		q = p->next;
		p->next = q->next;
		q->next = tail->next;
		tail->next = q;
	}
}

void ShiftList(node*head, int k,int n)
{
	RotateList(head, 1, k);
	RotateList(head, k+1, n);
}
时间复杂度为O(n),空间复杂度为O(1)

猜你喜欢

转载自blog.csdn.net/y___y___/article/details/44597665