问题9:编程实现一个单链表的建立/测长/打印以及结点的删除。

来源:互联网 发布:java蜘蛛爬虫 编辑:程序博客网 时间:2024/06/07 17:03

此题为一基本的数据结构方面的题目,主要考查单链表。

代码如下:

/** *  功能:单链表创建、测长打印 *  作者:ahnselina */#include <stdio.h>typedef struct student{  int data;  struct student *next;}node;//建立单链表node *creat(){   node *head, *p, *s;   int x, cycle = 1;   //建立头结点   head = (node*)malloc(sizeof(node));   p = head;   while(cycle)   {      printf("\nplease enter the data: ");  scanf("%d", &x);  if(x != 0)  {     //新建一个结点     s = (node*)malloc(sizeof(node)); s->data = x; printf("\n    %d",  s->data); p->next = s; p = s;  }   else     cycle = 0;   }   head = head -> next;   p->next = NULL;   printf("\n链表第一个结点值为:    %d", head->data);   return head;}//单链表测长int length(node *head){   int len = 0;   node *p = head;   while(p != NULL)   {       len++; p = p->next;   }   return len;}//单链表打印void print(node *head){  node *p = head;  int n = length(head);  printf("\nNow, These %d records are:\n", n);  while(p != NULL)  {     printf("\n     uuu  %d    ", p->data); p = p->next;  }}int main(void){  printf("===========NOW CREAT A LIST=========\n");  node *p = creat();  printf("\n下面计算链表长度:");  int len = length(p);  printf("\n链表长度为: %d", len);  printf("\n下面打印该单链表:");  print(p);  return 0;}


程序运行结果:


加入结点删除后的代码如下:

/** *  功能:单链表创建、测长打印 *  作者:ahnselina */#include <stdio.h>typedef struct student{  int data;  struct student *next;}node;//建立单链表node *creat(){   node *head, *p, *s;   int x, cycle = 1;   //建立头结点   head = (node*)malloc(sizeof(node));   p = head;   while(cycle)   {      printf("\nplease enter the data: ");  scanf("%d", &x);  if(x != 0)  {     //新建一个结点     s = (node*)malloc(sizeof(node)); s->data = x; printf("\n    %d",  s->data); p->next = s; p = s;  }   else     cycle = 0;   }   head = head -> next;   p->next = NULL;   printf("\n链表第一个结点值为:    %d", head->data);   return head;}//单链表测长int length(node *head){   int len = 0;   node *p = head;   while(p != NULL)   {       len++; p = p->next;   }   return len;}//单链表打印void print(node *head){  node *p = head;  int n = length(head);  printf("\nNow, These %d records are:\n", n);  while(p != NULL)  {     printf("\n     uuu  %d    ", p->data); p = p->next;  }}//删除单链表一个结点node *del(node *head, int num){  node *p1, *p2;  p1 = head;  while(num != p1->data && p1->next != NULL)  {     p2 = p1; p1 = p1->next;  }  if(num == p1->data)  {     if(p1 == head) {    head = p1->next;free(p1); } else {       p2->next = p1->next;free(p1); }  }  else      printf("\n %d不存在", num);  return head;}int main(void){  printf("===========NOW CREAT A LIST=========\n");  node *p = creat();  printf("\n下面计算链表长度:");  int len = length(p);  printf("\n链表长度为: %d", len);  printf("\n下面打印该单链表:");  print(p);  node *q = del(p, 4);  printf("\n删除结点后的链表为:\n");  print(q);  return 0;}
运行结果:



PS:在我最开始的程序里面,编译的时候出现错误

error: stray '\243' in program

这是因为有非标ascII的字符,字符一般都是全角符号什么的比如{ } 和{} ,和,

注意切换下输入法就好了

原创粉丝点击