【链表操作】链表长度
#include <stdio.h>
#include <stdlib.h>struct node {char data;struct node *next;
};int length(struct node* head);
void destroy(struct node* head);
struct node* headinsert(void);int main() {struct node *head;head = headinsert(); //用尾插法创建链表printf("%d", length(head));//释放资源destroy(head);return 0;
}struct node* headinsert(void) {struct node* head = NULL;char c;struct node *p, *q;while (1) {c = getchar();if (c == '#') break;//申请结点空间p = (struct node *)malloc(sizeof(struct node));//初始化结点数据域p->next = NULL;p->data = c;//尾插法q = head;if (q == NULL) {head = p;} else {while (q->next!= NULL) {q = q->next;}q->next = p;}}return head;
}int length(struct node* head) {int count = 0;struct node* p = head;while (p!= NULL) {count++;p = p->next;}return count;
}void destroy(struct node* head) {struct node *p;while (head!= NULL) {p = head; //p指向要销毁的结点head = head->next; //head指向再下一个要销毁的结点free(p); //销毁p指向的结点}
}
设计函数int length(struct node * head);,根据链表的头指针head,计算链表的长度(即结点个数)并返回该长度。
一行字符,以#结尾,将以#前的每个字符(不包括#)为数据域的值创建多个结点,并将这些结点,利用尾插法链接成链表