單鏈表

實現動態鏈表的創建、刪除、插入釋放等功能

#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)

int n;
struct student
{
  char name[15];
  int score;
  struct student *next;
};

struct student *creat()
{
  struct student*p2,*p1,*head;
  n=0;
  p1 = p2 = (struct student *)malloc(LEN);
  scanf ("%s",&(p1->name));
  scanf ("%d",&(p1->score));
  head = NULL;
  while(p1->score!=0)
  {
    if((++n)==1) head=p1;
    else p2->next=p1;
    p2=p1;
    p1 = (struct student *) malloc (LEN);
    scanf ("%s",&(p1->name));
    scanf ("%d",&(p1->score));
  }
  p2->next = NULL;
  return(head);
}

void print(struct student *head)
{
  struct student *p;
  p=head;
  if(head!=NULL)
  do
  {
    printf("%s  %d\n",p->name,p->score);
    p=p->next;
  } while(p!=NULL);
}

void my_free(struct student *head)
{
  struct student *p;
  while(head != NULL)
  {
    p = head;
    head = head->next;
    free(p);
    p = NULL;
  }
}

void del(struct student *head,int n)
{
  struct student *p_curr,*p_last;
  int num = 1;
  p_curr = head;
  while(p_curr != NULL)
  {
    num++;
    p_last = p_curr;
    p_curr = p_curr->next;
    if(num == n)
    {
      p_last->next = p_curr->next;
      free(p_curr);
      p_curr = NULL;
    }
  }
}

void insert(struct student *head, int n, char str_name[], int e)
{
  struct student *p_last,*p_curr,*p_inst;
  int num = 1;
  p_inst = (struct student *)malloc(sizeof(struct student));
  strcpy(p_inst->name, str_name);//字符數組的複製所用的函數
  p_inst->score = e;
  p_inst->next = NULL;

  p_curr = head;
  while(p_curr->next != NULL)
  {
    num++;
    p_last = p_curr;
    p_curr = p_curr->next;
    if(num == n)
    {
      p_last->next = p_inst;
      p_inst->next = p_curr;
      break;//一定要有這個,執行完這個就不在執行下去了
    }
  }
}

void main()
{
  struct student *head;
  head=creat();
  print(head);
  del(head,2);
  print(head);
  insert(head, 2, "sun", 99);
  print(head);
  my_free(head);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章