链表中节点移动---回归基础

题目描述

给定一定N长度的链表,节点数据由(1 ~ N)构成,再给定一个整数M(<1000000),表示有M个移动操作,每一个操作由一个字符和两个整数构成。

例:

L 1 4 				把数据域为1的节点移动到数据域为4的节点左边
R 2 1				把数据域为2的节点移动到数据域为1的节点右边

题目分析

做三个函数,第一个删除移动节点,第二个重构删除节点放到目标节点左边,第三个重构删除节点放到目标节点右边。其实这样做很多此一举,但是为了偷懒,就不想太多了。有时间的可以自己实现一下,反正实现不难。

代码实现

#include<iostream>
#include<cstdio>
#include<cstdlib>

using namespace std;

struct Node {
	int data;
	Node* next;
};

Node* createNode(int data) {						//创建节点
	Node* node = (Node*)malloc(sizeof(Node));
	node->data = data;
	node->next = NULL;
	return node;
}

void DeleteNode(int x, Node* head) {				//删除节点
	Node* temp;
	Node* p = head;
	while (p->next != NULL)
	{
		if (p->next->data == x) {
			temp = p->next;
			p->next = p->next->next;
			free(temp);
			return;
		}
	}
	printf("找不到参数x");
}

void InsertLeft(int x, int y, Node* head) {			//移左
	DeleteNode(x, head);							//调用删除节点函数
	Node* p = head;
	Node* node = createNode(x);
	while (p != NULL) {
		if (p->next->data == y) {
			node->next = p->next;
			p->next = node;
			return;
		}
		p = p->next;
	}
	printf("找不到参数y");
}

void InsertRight(int x, int y, Node* head) {		//移右
	DeleteNode(x, head);							//调用删除节点函数
	Node* p = head->next;
	Node* node = createNode(x);
	while (p != NULL) {
		if (p->data == y) {
			node->next = p->next;
			p->next = node;
			return;
		}
		p = p->next;
	}
	printf("找不到参数y");
}

void print(Node* head) {						//打印函数
	Node* p = head->next;
	while (p  != NULL)
	{
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
}

void freeAll(Node* head) {						//清空内存
	Node* temp;
	while (head != NULL)
	{
		temp = head;
		head = head->next;
		free(temp);
	}
}

int main(){
	char choose;								//选择字符
	int n, m, data, x, y;
	Node* p;
	Node* head = createNode(NULL);
	p = head;
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		p->next = createNode(i);
		p = p->next;
	}
	while (m--) {
		cin >> choose >> x >> y;
		if (choose == 'L') InsertLeft(x, y, head);
		else if (choose == 'R') InsertRight(x, y, head);
		else printf("操作字符不合法");
		print(head);
	}
	freeAll(head);
	return 0;
}

效果实现

在这里插入图片描述

题外话

有时候做多了动态规划觉得自己做这些基础题目会很简单,但是没想到太久没做并且基础不算太扎实,做起来还费了点时间,所以一定要在一个月内把基础重新打捞一遍,有时候错的就是你不在意的一个小细节,努力吧,哪怕没人看hhh,12月CCF冲冲冲。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值