#include<stdio.h>
#include<stdlib.h>struct link{int data;struct link *next;
};void DisplayNode(struct link *head)
{struct link *p = head;int j = 1;while(p != NULL){printf("%5d%10dn", j, p->data);p = p->next;j++;}
}
void DeleteMemory(struct link *head)
{struct link *p = head, *pr = NULL;while(p != NULL){pr = p;p = p->next;free(pr);}
}
struct link *AppendNode(struct link *head) // 返回指针,
{struct link *p = NULL, *pr = head;int data;p = (struct link *) malloc(sizeof(struct link));if (p == NULL){printf("No enough memory to allocate!n");exit(0);}if (head == NULL) // 若原链表为空表 {head = p; // 将新建节点置为头节点. }else // 若原链表为非空, 则将新建节点添加到表尾 {while(pr->next != NULL){pr = pr->next; // 然pr指向下一个结点 } pr->next = p; // 然末节点的指针域指向新建节点 } printf("Input node data:") ;scanf("%d", &data);p->data = data;p->next = NULL; // 将新建节点置为表尾 return head;
}
struct link *DeleteNode(struct link *head, int x)
{struct link *p = head, *pr = head; // 先让 p就位!!!! p就是要删除的结点, pr是p的前驱结点. while(p != NULL && p->data != x) // 这思路可以啊, 找到待删除结点, 后续再做删除处理. {pr = p;p = p->next; }if (p->data == x){if (p == head){head = p->next;}else{pr->next = p->next; } free(p);}else // 妙啊 {printf("This Node has not been found! n");}return head;
}
int main(void)
{int i = 0;char c;struct link *head = NULL; // 链表头指针!!! printf("Do you want to append a new node(Y/N)?") ;scanf(" %c", &c);while(c == 'Y' || c == 'y'){head = AppendNode(head); // 向head为头指针的链表的末尾添加结点. DisplayNode(head);printf("Do you want to append a new node(Y/N)?");scanf(" %c", &c); // %c前有空格!!! i++;}printf("%d new node have been appended! n", i);DeleteMemory(head);
}
本文发布于:2024-01-30 03:50:06,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170655780819020.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |