欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言实现链表

程序员文章站 2024-01-09 16:48:04
...
大作业水平...
#include<stdio.h>
#include<stdlib.h>

struct node{
    struct node* next;
    int c;
};

struct node* init_node(int input)
{
    struct node* p;
    p = malloc(sizeof(struct node));
    p->c = input;
    return p;
}

void insert_node(struct node *head, int new)
{
    struct node *temp = (struct node*)(malloc(sizeof(struct node)));
//    struct node *temp;
    while(head->next != NULL)
        head = head->next;
    head->next = temp;
    temp->c = new;
    temp->next = NULL;
}

void display_list(struct node* head){
    if(head == NULL)
    {
      printf("error.\n");
      return;
    }
    struct node *p = head;
    while(p->next != NULL)
    {
        printf("%d ",p->c);
        p = p->next;
    }
    printf("%d ", p->c);
    printf("NULL\n");
}

void destroy_list(struct node *head)
{
    if (NULL != head) {
        destroy_list(head->next);
//        free(head->c);
        free(head);
        printf("destroy a list...\n");
    }
}

struct node* copy_list(struct node* head)
{
  struct node* p = (struct node*)(malloc(sizeof(struct node)));
  p->next = NULL;
  if(head == NULL)
  {
    printf("head is NULL.\n");
    return;
  }
  p->c = head->c;
  head = head->next;
  while(head != NULL)
  {
    printf("copying... head->c: %d\n", head->c);
    insert_node(p, head->c);
    head = head->next;
  }
//  insert_node(p, head->c);
  return p;
}

struct node* reverse_list(struct node* head)
{
  struct node* p;
  struct node* t;
  p = (struct node*)(malloc(sizeof(struct node)));
  p->c = head->c;
  p->next = NULL;
  while(head->next != NULL)
  {
    head = head->next;
    t = p;
    p = (struct node*)(malloc(sizeof(struct node)));
    p->next = t;
    p->c = head->c;
  }
  return p;
}

int main(int argc, char** argv)
{
    struct node *head = init_node(1);
    long long i;
    insert_node(head, 2);
    insert_node(head, 3);
    insert_node(head, 4);
    insert_node(head, 5);
    insert_node(head, 6);
    insert_node(head, 7);
    display_list(head);
    struct node* copy = copy_list(head);
    printf("copy done.\n");
    struct node* reve = reverse_list(head);
    display_list(reve);
    for (i = 0; i < 0x1000000; i++) reve = reverse_list(head);
    display_list(reve);
    display_list(copy);
    destroy_list(head);
    destroy_list(copy);
    return 0;
}

相关标签: c

上一篇:

下一篇: