链表的k子段逆转

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

题目:

原链表为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=pos
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
单向链表的就地逆转是指在不创建新的链表节点的情况下,将原链表的节点顺序反转。下面是一个C语言实现的单向链表就地逆转的代码: ```c #include <stdio.h> #include <stdlib.h> // 链表节点结构体 struct Node { int data; struct Node* next; }; // 创建新节点 struct Node* createNode(int data) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); if (newNode == NULL) { printf("内存分配失败\n"); exit(1); } newNode->data = data; newNode->next = NULL; return newNode; } // 将链表节点逆转 struct Node* reverseList(struct Node* head) { struct Node* prev = NULL; struct Node* current = head; struct Node* next = NULL; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } return prev; } // 打印链表 void printList(struct Node* head) { struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n"); } int main() { // 创建链表 struct Node* head = createNode(1); head->next = createNode(2); head->next->next = createNode(3); head->next->next->next = createNode(4); head->next->next->next->next = createNode(5); printf("原链表:"); printList(head); // 将链表逆转 head = reverseList(head); printf("逆转后的链表:"); printList(head); return 0; } ``` 这段代码首先义了一个链表节点的结构体,包含数据和指向下一个节点的指针。然后义了创建新节点的函数`createNode`,用于创建新的链表节点。接下来是`reverseList`函数,用于将链表节点逆转。最后是`printList`函数,用于打印链表。 在`main`函数,我们创建了一个包含5个节点的链表,并打印原链表。然后调用`reverseList`函数将链表逆转,并再次打印逆转后的链表。 运行以上代码,输出结果为: ``` 原链表:1 2 3 4 5 逆转后的链表:5 4 3 2 1 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值