- 【问题描述】
输入n(n>1)个整数,每次将输入的整数插入到链表头部。-1表示输入结束。再输入一个整数,在链表中查找该数据并删除对应的节点。要求输出惊醒删除操作后链表中所有节点的值。 - 【输入形式】
输入以空格分割的n个整数,以-1结束,在输入一个需要删除的数。 - 【输出形式】
从链表第一个元素开始,输出链表中所有节点的值。以空格分割。 - 【样例输入】
2 4 6 7 8 4 -1
2 - 【样例输出】
4 8 7 6 4 - 自做答案1
//2020/4/4 //使用带有头结点的链表 #include<stdio.h> #include<stdlib.h> typedef struct Node {
int data; Node *next; }Node; void insert_head(Node *head,int x) {
Node *p,*s; p = head; s = (Node*)malloc(sizeof(Node)); s->data = x; s->next = p->next; p->next = s; } void print(Node* head) {
Node* p = head->next; while(p) {
if(p->next == NULL) {
printf("%d\n",p->data); } else printf("%d ",p->data); p = p->next; } } void del_all(Node* head,int data) {
Node *p,*q; p = head->next; q = head; while(p) {
if(p->data == data) {
q->next = p->next; free(p); p = q->next; } else {
q = p; p = p->next; } } } int main() {
Node *head = (Node*)malloc(sizeof(Node)); head->next = NULL; int tmp_data; scanf("%d",&tmp_data); while(tmp_data != -1) {
insert_head(head,tmp_data); scanf("%d",&tmp_data); } print(head); scanf("%d",&tmp_data); del_all(head,tmp_data); print(head); return 0; }
讯享网
-自做答案2:
讯享网#include<stdio.h> #include<stdlib.h> //使用不带有头结点的链表 struct Node {
int data; Node* next; }; //在刚开始建立链表的时候与有头结点的写法有区别 Node* insert_head(Node *head,int x)//头指针的指向有可能发生改变,需要使用引用或者返回来修改head {
if(head == NULL) {
head = (Node*)malloc(sizeof(Node)); head->data = x; head->next = NULL; return head; } else {
Node* s; s = (Node*)malloc(sizeof(Node)); s->data = x; s->next = head; head = s; return head; } } Node* del_one(Node *head,int x) {
Node* p; Node* tmp; if(head->data == x) {
tmp = head; head = head->next; free(tmp); return head; } else {
p = head; while(p->next) {
if(p->next->data == x) {
tmp = p->next; p->next = p->next->next; free(tmp); return head;// } p = p->next; } return head; } } void print(Node* head) {
Node *p = head; while(p) {
if(p->next == NULL) {
printf("%d\n",p->data); } else {
printf("%d ",p->data); } p = p->next; } } int main() {
int tmp_data; Node* head = NULL; scanf("%d",&tmp_data); while(tmp_data != -1) {
head = insert_head(head,tmp_data); scanf("%d",&tmp_data); } print(head); scanf("%d",&tmp_data); del_one(head,tmp_data); print(head); return 0; }
- 小结:带有头结点和不带有头结点的链表在插入和删除操作的时候有所不同。(不带头结点的head头指针有可能会发生改变,需要单独处理第一个元元素)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/54477.html