单向链表学习笔记一

单向链表的创建:有头节点和无头结点的插入创建方法;

  1 #include<cstdio>
  2 #include <iostream>
  3 using namespace std;
  4 typedef struct LNode {
  5     int data;
  6     struct LNode* next;
  7 }LNode,*LinkList;
  8 bool InitList(LinkList& L)//不带头节点;
  9 {
 10     L = NULL;
 11     return true;
 12 }
 13 bool InitList1(LinkList& L)//带头结点,对数据操作更简单,方便;
 14 {
 15     L = new LNode;
 16     if (L->next == NULL)
 17         return false;
 18     L->next = NULL;
 19     return true;
 20 }
 21 /********带头结点的头插法头指针动,尾插法头指针不动********/
 22 LinkList List_RearInsert_Creat(LinkList& L)//带头结点的尾插法创建链表(正序链表)
 23 {
 24     LNode* p,*s;
 25     s = L;
 26     int Data;
 27     cin >> Data;
 28     while (Data != 222)
 29     {
 30         p = new LNode;
 31         p->data = Data;
 32         s->next = p;
 33         s= p;
 34         cin >> Data;
 35     }
 36     s->next = NULL;
 37     return s;
 38 }
 39 LinkList List_HeadInsert_Creat(LinkList& L)//带头节点的头插法链表创建(逆序链表)
 40 {
 41     LNode* p;
 42     int Data;
 43     cin >> Data;
 44     while (Data != 222)
 45     {
 46         p = new LNode;
 47         p->data = Data;
 48         p->next = L->next;
 49         L->next = p;
 50         cin >> Data;
 51     }
 52     return L;
 53 }
 54 /******************不带头节点的头插法,尾插法*******************/
 55 LinkList List_head_list(LinkList& L)
 56 {
 57     LNode* p;
 58     int Data;
 59     cin >> Data;
 60     while (Data != 222)
 61     {
 62         p = new LNode;
 63         p->data = Data;
 64         if (NULL == p)
 65             perror("Error exists");
 66         p->next = L;
 67         L = p;
 68         cin >> Data;
 69     }
 70     return L;
 71 }
 72 /*******************不带头结点的尾插法************************/
 73 LinkList List_Rear_list(LinkList& L) 
 74 {
 75     LNode* rear, * s;
 76     rear = L;
 77     int Data;
 78     cin >> Data;
 79     while (Data!=222)
 80     {
 81         s = new LNode;
 82         s->data = Data;
 83         if (NULL == L) L = s;
 84         else rear->next = s;
 85         rear = s;
 86         cin >> Data;
 87     }
 88     rear->next = NULL;
 89     return rear;
 90 }
 91 int main()
 92 {
 93     LinkList L=NULL;
 94     //InitList1(L);
 95     //LNode* s = L;
 96     /*List_RearInsert_Creat(L);
 97     List_HeadInsert_Creat(L);
 98     while (s->next != NULL)
 99     {
100         s = s->next;
101         cout << s->data << endl;
102     }*/
103     //List_head_list(L);
104     List_Rear_list(L);
105     LNode* s = L;
106     while (s != NULL)
107     {
108         cout << s->data << endl;
109         s = s->next;
110     }
111     return true;
112 }
113 /*如果在链表的开始结点之前附加一个结点,并称它为头结点,那么会带来以下两个优点:
114 a、由于开始结点的位置被存放在头结点的指针域中,
115 所以在链表的第一个位置上的操作就和在表的其它位置上
116 的操作一致,无需进行特殊处理;
117 b、无论链表是否为空,其头指针是指向头结点在的
118 非空指针(空表中头结点的指针域为空),因此空表和
119 非空表的处理也就统一了。*/

 

posted @ 2021-07-11 22:28  Mexcellent  阅读(36)  评论(0)    收藏  举报