码迷,mamicode.com
首页 > 编程语言 > 详细

单链表C++实现

时间:2019-12-11 00:47:42      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:初始化   clu   def   pre   main   实现   null   name   ios   

  1 // ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
  2 //
  3 
  4 #include "stdafx.h"
  5 #include"iostream"
  6 using namespace std;
  7 
  8 typedef int data;
  9 
 10 typedef struct node_list
 11 {
 12     data info;;
 13     node_list *next;
 14 }node;
 15 
 16 node *init();
 17 node *insert_head(node *head, data x);
 18 node *insert_rear(node *head, data x);
 19 node *insert_x(node *head, data x, data y);
 20 node *del_x(node *head, data x);
 21 int print(node *p);
 22 
 23 int _tmain(int argc, _TCHAR* argv[])
 24 {
 25 
 26     node *p = init();
 27 
 28     p=insert_head(p,1);
 29     
 30     for (int i = 0; i < 10;i++)
 31         p = insert_rear(p, i);
 32 
 33 
 34     p=insert_x(p, 5, 1000);
 35     print(p);
 36 
 37 
 38     p = del_x(p,1000);
 39     print(p);
 40     return 0;
 41 }
 42 
 43 node *init()
 44 {
 45     return NULL;
 46 }
 47 
 48 
 49 node *insert_head(node *head,data x)
 50 {
 51     head = (node*)malloc(sizeof(node));
 52     head->info = x;
 53     head->next=NULL;
 54     return head;
 55 }
 56 
 57 
 58 node *insert_rear(node *head, data x)
 59 {
 60     node *q = head;
 61     
 62     while (q->next!= NULL)
 63         q = q->next;
 64 
 65     node *p = (node *)malloc(sizeof(node));
 66     q->next = p;
 67     q->next->info = x;
 68     p->next = NULL;//注意初始化
 69     return head;
 70 }
 71 
 72 int print(node *p)
 73 {
 74     if (p == NULL)
 75         cout << "It is empty!" << endl;
 76     else
 77     while (p!=NULL)
 78     {
 79         cout << p->info << endl;
 80         p = p->next;
 81     }
 82 
 83     return 0;
 84 }
 85 
 86 
 87 node *insert_x(node *head, data x,data y)
 88 {
 89     node *p = head;
 90     node *q = (node *)malloc(sizeof(node));
 91     q->info = y;
 92     while (p->info != x)
 93         p = p->next;
 94     q->next = p->next;
 95     p->next = q;
 96 
 97     return head;
 98 }
 99 
100 
101 node *del_x(node *head, data x)
102 {
103     node *q = head;
104     while (q->next->info != x)
105         q = q->next;
106     q->next = q->next->next;
107     
108     return head;
109 }

指针没有初始化,找了半天问题,MD!

单链表C++实现

标签:初始化   clu   def   pre   main   实现   null   name   ios   

原文地址:https://www.cnblogs.com/butchert/p/12019660.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!