苏小红C语言链表模板

阅读: 评论:0

苏小红C语言链表模板

苏小红C语言链表模板

链表模板

#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 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23