数据结构——单链表

简介: 数据结构——单链表


目录

建立节点

初始化

尾插法建立单链表

头插法建立单链表

单链表的遍历

单链表的查询

单链表的删除

单链表的插入

        单链表的逆序(三指针法)

链表的销毁


建立节点

typedef struct node
{
  char name[20]; //姓名
  int number;  //学号
  struct node* next;//指针域
}Node;

初始化

Node* InitList()
{
  Node* head;
  head = (Node*)malloc(sizeof(Node));
  head->next = NULL;
  return head;
}

尾插法建立单链表

void CreatByRear(Node* head)
{
  Node* r, * s;
  char name[20];
  int number;
  r = head;
  while (1)
  {
    scanf("%s", name);
    scanf("%d", &number);
    if (number == 0)
      break;
    s = (Node*)malloc(sizeof(Node));
    strcpy(s->name, name);
    s->number = number;
    r->next = s;//原来的节点指向新节点
    r = s;//r指向新的节点
  }
  r->next = NULL;
}

头插法建立单链表

void CreatByHead(Node* head)
{
  Node* s;
  char name[20];
  int number;
  printf("请输入学生的姓名和学号");
  while (1)
  {
    scanf("%s", name);
    scanf("%d", &number);
    if (number == 0)
      break;
    s = (Node*)malloc(sizeof(Node));
    strcpy(s->name, name);
    s->number = number;
    s->next = head->next;
    head->next = s;
  }
}

单链表的遍历

void OutPut(Node*head)
{
  Node* p = head->next;
  while (p)
  {
    printf("姓名:  %s\n", p->name);
    printf("学号:  %d\n\n\n", p->number);
    p = p->next;
  }
}

单链表的查询

Node* FindNote(Node* head,int x)//查找第x个节点(包含头节点)
{
  Node* p = head;
  while (p && x > 1)
  {
    p = p->next;
    x--;
  }
  if (!p)
  {
    printf("该节点不存在");
  }
  else
    return p;
}

单链表的删除

void Delete(Node* head, int i)
{
    if (i == 1)//头删
  {
    Node* cur = head->next;
    head->next = cur->next;
    free(cur);
    return;
  }
  Node* p = FindNote(head, i-1);
  Node* q= FindNote(head, i);
  p->next = q->next;
  free(q);
}

单链表的插入

void Insert(Node* head, int i)
{
    printf("请输入要插入学生的姓名和学号");
    scanf("%s", s->name);
  scanf("%d", &s->number);
    Node* s = (Node*)malloc(sizeof(Node));
  Node* p = FindNote(head, i);
    if (k == 1)//头插
  {
    s->next = head->next;
    head->next = s;
    return;
  }
  s->next = p->next;
  p->next = s;
}

单链表的逆序(三指针法)

void Reverse(Node* head)
{
  Node* p,* q, *r=NULL;
  p = head->next;
  q = p->next;
  p->next = NULL;
  while (q)
  {
    r = q;
    q = q->next;
    r->next = p;
    p = r;
  }
  head->next = r;
}

链表的销毁

//链表的销毁
void DestoryList(Node*head)
{
  Node* p = head->next;
  Node* q = p;
  while (p)
  {
    p = p->next;
    free(q);
    q = p;
  }
}
相关文章
|
6天前
【数据结构】单链表(长期维护)(1)
【数据结构】单链表(长期维护)(1)
|
3月前
|
存储
[数据结构]——单链表——超详解
[数据结构]——单链表——超详解
|
12天前
|
存储
【数据结构】单链表-->详细讲解,后赋源码
【数据结构】单链表-->详细讲解,后赋源码
15 4
|
1天前
|
算法 索引
【初阶数据结构篇】单链表算法题进阶
深拷贝应该正好由 n 个全新节点组成,其中每个新节点的值都设为其对应的原节点的值。
|
6天前
【数据结构】单链表(长期维护)(2)
【数据结构】单链表(长期维护)(2)
|
1月前
|
存储 DataX C语言
【数据结构】单链表
数据结构中的单链表
18 0
【数据结构】单链表
|
2月前
|
存储 测试技术
【数据结构】最最基础的链式结构——单链表,还不会你就吃大亏了!
【数据结构】最最基础的链式结构——单链表,还不会你就吃大亏了!
30 5
|
2月前
|
算法 程序员 数据处理
【数据结构与算法】使用单链表实现队列:原理、步骤与应用
【数据结构与算法】使用单链表实现队列:原理、步骤与应用
|
2月前
|
算法 C语言
【数据结构与算法 经典例题】返回单链表的倒数第 k 个节点
【数据结构与算法 经典例题】返回单链表的倒数第 k 个节点
|
2月前
|
存储 算法 C语言
【数据结构与算法】深入理解 单链表
【数据结构与算法】深入理解 单链表