leetcode:K个一组反转链表

这篇博客介绍了如何在C++中实现一个链表操作,具体是按给定步长k翻转链表的子链。首先,定义了链表节点结构体并实现了初始化链表和打印链表的函数。接着,定义了一个`MyReverse`函数用于反转链表的子段,然后在`List_Part_Reverse`函数中,遍历链表并应用子链翻转。最后,通过示例展示了如何读取链表元素,翻转部分链表,并打印结果。
摘要由CSDN通过智能技术生成

给定一个带头结点的单链表L,k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。

示例

bb573ae0276344e2ae41e1ee75861c6e.png04a22e9231a245beba2e0f6c69ec9125.png

 

//库函数头文件包含
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
//函数状态码定义
#define TRUE        1
#define FALSE       0
#define OK          1
#define ERROR       0
#define INFEASIBLE -1
#define OVERFLOW   -2

typedef int  Status;
typedef int ElemType;

typedef struct LNode {
	ElemType data;
	struct LNode* next;
}LNode,*LinkList;

Status InitList(LinkList& L)
{
	L = new LNode;
	if (!L)exit(OVERFLOW);
	L->next = NULL;
	int n,t;
	LNode* pre = L, * cur = NULL;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> t;
		cur = new LNode;
		if (!cur)exit(OVERFLOW);
		cur->data = t;
		cur->next = pre->next;
		pre->next = cur;
		pre = pre->next;
	}
	return OK;
}
void ListPrint(LinkList& L)
{
	LNode* p = L->next;
	while (p)
	{
		if (p->next)
			cout << p->data << " ";
		else
			cout << p->data;
		p = p->next;
	}
	cout << endl;
}
void MyReverse(LinkList& head, LinkList& tail)//实现子链的反转
{
	LNode* prev = tail->next, *p = head;
	while (prev != tail)
	{
		LNode* nex = p->next;
		p->next = prev;
		prev = p;
		p = nex;
	}
	LNode* t = head; head = tail; tail = t; t = NULL;
}
void List_Part_Reverse(LinkList& L, int k)
{
	LNode* pre = L,*one=L->next;
	while (one)
	{
		LNode* tail = pre;
		for (int i = 0; i < k; i++)//剩余是否够k个
		{
			tail = tail->next;
			if (!tail)return;
		}
		LNode* nex = tail->next;
		MyReverse(one, tail);
		pre->next = one;
		tail->next = nex;
		pre = tail;
		one = tail->next;
	}
}
int main()
{
	int k;
	LinkList L;
	InitList(L);
	ListPrint(L);
	cin >> k;
	List_Part_Reverse(L,k);
	ListPrint(L);
	return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值