链表

今天做美团笔试,第二题就,题目大概是:对于一串n个数字:1,2…n,给一串操作,每次把指定的数字移动到最左边(最前面),输出最后的结果

很明显,最直接的想法肯定就是模拟一个链表,每次把链表中的指定节点移动到链表头的位置

看起来这是很简单基础的对吧

但事实上自己做起来却是如此的不熟练,让我觉得其实自己根本就没有掌握链表于是有了这一篇,前事不忘后事之师

构造一串链表

#include <iostream>
#include <vector>
using namespace std;

struct ListNode {
	int val;
	ListNode* next;

	ListNode():val(),next(nullptr) {}
	ListNode(int value, ListNode* next) :val(value), next(next) {}
	ListNode(int value) :val(value), next(nullptr) {}
};

class LinkedList {
public:
	// 递归,从尾到头构造
	// 给一个数字,构造从1到n的链表出来
    // 返回链表的头指针
	ListNode* createLinkedList(int n) {
		// 只能从后往前构造
		ListNode* tail = new ListNode(n);
		ListNode* head = create(tail, n - 1);
		return head;
	}

	ListNode* create(ListNode* node, int n) {
		if (node->val == 1) return node;
		ListNode* newNode = new ListNode(node->val -1);
		newNode->next = node;
		create(newNode, n);
	}

	// 头插循环构造,从头到尾,需要一个虚拟头节点
	// 给一个数组,构造对应的链表出来
    // 返回链表头指针
	ListNode* createLinkedList(vector<int>& nums) {
		ListNode* virtualHead = new ListNode();
		for (int i : nums) {
			ListNode* node = new ListNode(i);
			node->next = virtualHead->next;
			virtualHead->next = node;
		}
		return virtualHead->next;
	}

	// 打印链表
	void printLinkedList(ListNode* head) {
		if (head==NULL) return;
		// printf("%d ", head->val);
		cout << head->val << " ";
		printLinkedList(head->next);
	}
};

int main() {

	LinkedList linkedList;
	//ListNode* head = linkedList.createLinkedList(5);
	//linkedList.printLinkedList(head);

	vector<int> nums = { 9,0 };
	ListNode* head = linkedList.createLinkedList(nums);
	linkedList.printLinkedList(head);

	return 0;
}

LRU

我突然意识到这道理就是LRU啊

posted @ 2022-08-27 22:42  YaosGHC  阅读(22)  评论(0)    收藏  举报