题目描述
设计函数void prevnext(struct node * head, char x);,在以head为头指针的非空链表中,找到数据域值为x的结点,输出该结点的前一个结点和后一个结点的数据域值,如果该结点没有前驱结点(即该结点为第1个结点),则以-1代替,如果该结点没有后继结点(即该结点为尾结点),也以-1代替,如果该结点既是第1个结点也是尾结点(即只有1个结点的链表),则输出2个-1。如果找不到这样的结点,则输出"no node"。
输入
第一行为若干个互不相同的整数,中间用空格分隔,末尾一个整数为-1,以-1前的每个整数为数据域的值创建多个结点,并将这些结点,利用尾插法链接成链表。
第2行为1个整数,表示要查找的结点的数据域的值。
输出
查找到的结点的前驱和后继的数据域值。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
void prevnext(struct node *head, int x);
void destroy(struct node* head);
struct node* creatlink();
void traverse(struct node* head);
int main() {
int c;
struct node *head;
head = creatlink();
scanf("%d", &c);
prevnext(head, c);
destroy(head);
return 0;
}
void prevnext(struct node *head, int x) {
struct node *prev, *p;
p = head;
prev = NULL;
while (p!= NULL) {
if (p->data == x) {
if (prev == NULL) {
printf("-1 ");
} else {
printf("%d ", prev->data);
}
if (p->next == NULL) {
printf("-1");
} else {
printf("%d", p->next->data);
}
return;
}
prev = p;
p = p->next;
}
printf("no node");
}
struct node* creatlink() {
struct node* head = NULL;
int data;
struct node *p, *q;
while (1) {
scanf("%d", &data);
if (data == -1) break;
p = (struct node *)malloc(sizeof(struct node));
p->next = NULL;
p->data = data;
q = head;
if (q == NULL) {
head = p;
} else {
while (q->next!= NULL) {
q = q->next;
}
q->next = p;
}
}
return head;
}
void traverse(struct node* head) {
struct node *p = head;
while (p!= NULL) {
printf("%d ", p->data);
p = p->next;
}
}
//销毁链表
void destroy(struct node* head) {
struct node *p;
while (head!= NULL) {
p = head;
head = head->next;
free(p);
}
}
标签:node,head,struct,结点,后继,链表,前驱,NULL,data
From: https://blog.csdn.net/2302_80782671/article/details/142470005