链表的k子段逆转

博客探讨了如何对链表进行k子段逆转操作,例如原链表1->2->3->4->5->6->7,在k=3的情况下,逆转后的结果为3->2->1->6->5->4->7。实现过程中,关键点在于记录整个链表的头指针及相邻子段的尾节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

原链表为1->2->3->4->5->6->7

k=3的子段逆转结果为

3->2->1->6->5->4->7


code:

关键点
首子段要记录整个链表的头指针,记录相邻两字段的尾节点

#include "stdafx.h"
#include <vector>
#include <iostream>
#include <hash_map>
using namespace std;

typedef struct node
{
	int data;
	struct node* next;
}*pList,Node;

void rReverse(pList &list,int k)
{
	pList p=list, tail, pretail;
	tail=p;
	int flag=0;
	while(p!=NULL)
	{
		int n=k;
		pList post=p->next;
		tail=p;
		
		while(post!=NULL && n--!=1)
		{
			pList temp=post->next;
			post->next=p;
			p=post;
			post=temp;
		}

		if(post!=NULL && flag==0)
		{
			list=p;
			pretail=tail;
			flag=1;
			p=post;
		}
		else if(post!=NULL)
		{
			pretail->next=p;
			pretail=tail;
			p=post;
		}
		else
		{
			pretail->next=p;
			tail->next=NULL;
			break;
		}
	}
}

int s[7]={1,2,3,4,5,6,7};

void createList(pList& head)
{
	head=new Node;
	pList p=head;

	for(int i=0;i<7;i++)
	{
		p->next=new Node;
		p->next->data=s[i];
		p=p->next;
	}
	p->next=NULL;

	p=head;
	head=head->next;
	delete p;
}

void showList(pList head)
{
	pList p=head;

	while(p!=NULL)
	{
		cout<<p->data<<" ";
		p=p->next;
	}
	cout<<endl;
}

int main(void)
{
	pList head;

	createList(head);
	showList(head);
	rReverse(head,4);
	showList(head);

	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值