社区讨论

80pts

B3631单向链表参与者 1已保存回复 0

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
0 条
当前快照
1 份
快照标识符
@lvmd94q1
此快照首次捕获于
2024/04/30 20:30
2 年前
此快照最后确认于
2024/04/30 22:42
2 年前
查看原帖
虽然现在已经满分了
但还是想问一下:
CPP
#include<bits/stdc++.h>
using namespace std;
typedef struct Node {
   int value;
   struct Node* next;
}Node;

Node* head = NULL;
void charu(int x, int y)
{
   Node* newNode = (Node*)malloc(sizeof(Node));
   if (newNode == NULL) {
   	printf("Memory allocation failed.\n");
   	exit(1);
   }
   newNode->value = y;
   Node* p = head;
   while (p != NULL&&p->value !=x) {
   	p = p->next;
   }
   if (p->value != NULL) {
   	newNode->next = p->next;
   	p->next = newNode;
   }
   else {
   	printf("Element %d not found in the list.\n", x);
   }
}

int chaxun(int x)
{
   Node* p = head;
   while (p != NULL && p->value != x)
   	p = p->next;
   if (p != NULL && p->next != NULL) {
   	return p->next->value;
   }
   else return 0;
}


void shanchu(int x)
{
   Node* p = head;
   while (p != NULL && p->value!=x)
   	p = p->next;
   if (p != NULL && p->next != NULL) {
   	Node* q = p->next;
   	p->next = q->next;
   	free(q);
   }
   else  printf("Element %d or its successor is not found in the list.\n", x);//自己翻译吧
}
int main()
{
   head = (Node*)malloc(sizeof(Node));
   head->value = 1;
   head->next = NULL;

   int n;
   scanf("%d", &n);
   while (n--) {
   	int m, x, y;
   	scanf("%d%d", &m, &x);
   	switch (m)
   	{
   	case 1:
   		scanf("%d", &y);
   		charu(x, y);
   		break;
   	case 2:
   		printf("%d\n", chaxun(x));
   		break;
   	case 3:
   		shanchu(x);
   		break;
   	default:printf("Invalid operation.\n");
   	}
   }
   return 0;
}

回复

0 条回复,欢迎继续交流。

正在加载回复...