练习 #4
Coddy 双向链表:数据结构系列 #6 课程的第 13 课,共 14 课。
挑战
简单编写一个函数 moveToFront,接收一个整数数组 arr(其中包含双向链表的值)和一个整数 value,找到 value 第一次出现的位置,并将该节点移到链表的开头。返回结果数组。
如果链表中没有 value,则原样返回该数组。
请使用双向链表解决这个问题!
你必须使用 DoublyLinkedList 类(该类与 node.<ext> 一起在 doublylinkedlist.<ext> 中提供)—不要使用语言内置功能,例如数组的反转、切片、排序,或标准库的列表操作来计算结果。
亲手试试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "solution.h"
int main() {
char line1[8192];
char line2[64];
if (!fgets(line1, sizeof(line1), stdin)) line1[0] = '\0';
if (!fgets(line2, sizeof(line2), stdin)) line2[0] = '\0';
int arr[4096];
int len = 0;
char* tok = strtok(line1, " \t\r\n");
while (tok) { arr[len++] = atoi(tok); tok = strtok(NULL, " \t\r\n"); }
int n = atoi(line2);
int rs = 0;
int* r = moveToFront(arr, len, n, &rs);
for (int idx = 0; idx < rs; idx++) {
if (idx > 0) printf(" ");
printf("%d", r[idx]);
}
printf("\n");
return 0;
}
双向链表:数据结构系列 #6中的所有课
自己练习: C 在线编译器