求帮助关于一个简单的链表实现

C语言 码拜 8年前 (2016-05-03) 778次浏览
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct node{
	int data;
	struct node * next;
};
struct node *  init(int data){
	struct node * head = (struct node *)malloc(sizeof(struct node *));
	struct node *  n = (struct node * )malloc(sizeof(struct node));
	n->data = data;
	n->next = NULL;
	head = n;
	return head;
}
void add2tail(struct node *  list, int data){
	struct node *  n = list;
	while (n != NULL){
		n = n->next;
	}
	struct node *  newnode = (struct node * )malloc(sizeof(struct node));
	n = newnode;
	newnode->data = data;
	newnode->next = NULL;
	return;
}
void print(struct node *  list){
	struct node *  n = list;
	while (n != NULL){
		printf("%d ", n->data);
		n = n->next;
	}
	printf("\n");
	return;
}
int main(void){
	struct node *  head = init(123);
	print(head);
	add2tail(head, 7);
	print(head);
	system("pause");
	return 0;
}

代码如上,本人的思路是init创建一个节点和一个指针(都在堆上面),然后返回这个指针作为head指针,add2tail就是向链表尾部添加节点,但是代码无法正常运行,本人想了很久都没能理解,只能求帮助各位高手

解决方案

50

引用:
Quote: 引用:
Quote: 引用:
Quote: 引用:
Quote: 引用:
Quote: 引用:
#include<iostream> 
#include<malloc.h>
using namespace std;
typedef struct Node
{
	int data;
	Node *next;
}Lnode,*List;
int Allocate(List &p) //必须要有引用,否则指针p分不到内存空间 
{
  p=(List)malloc(sizeof(Lnode));
  p->next=NULL;
  return 0;
}
int HeadCreatlist(List p1)  //头插法 
{
  List s;  
  Allocate(s);
  cout<<"Please input the data"<<endl;
  cin>>s->data;
  s->next=p1->next;
  p1->next=s;
  return 0;
}
int TailCreatlist(List &p3) //尾插法 
{
  List s; 
  Allocate(s);
  cout<<"Please input the data"<<endl;
  cin>>s->data;
  p3->next=s;
  p3=s;
  return 0;
}
int Travellist(List P) //遍历函数 
{
  List p=P->next;
  while(p!=NULL)
  {
  	cout<<p->data<<" ";
  	p=p->next;
  }
  return 0;
}
int main()
{
  List p1;
  int i;
  Allocate(p1);
  for(int i=0;i<4;i++)
  HeadCreatlist(p1);
  Travellist(p1); //头插法用的代码 
  
  List p2;
  Allocate(p2);
  List p3=p2; //尾插法用的存储当前指针 
 for(int i=0;i<4;i++)
 TailCreatlist(p3);
 Travellist(p2);//尾插法用的代码
  
 return 0;
}

本人想写的头插是直接在头部的上一个插入例如原来1->5->7头插一个9就变成了9->1->5->7
但是本人这样写为什么不对

void add2head(struct node * list, int data){
	struct node *  newnode = (struct node *)malloc(sizeof(struct node));
	newnode->data = data;
	newnode->next = list;
	list = newnode;
	return;
}

你要在add2head函数里改变list的指向,必须传二级指针或一级指针的引用才行

….感觉白看了c primer plus,话说为什么要传二级指针或一级的引用,有没有这方面的资料免得麻烦您了,本人一直就以为指针可以任意改变指向,实在不懂为什么还要二级指针才能改变参数的指向

那是原因是你的实参和形参并不是同一个指针,他们只是指向了同一块内存

明白了,感谢。

解决了记得结帖求帮助关于一个简单的链表实现


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明求帮助关于一个简单的链表实现
喜欢 (0)
[1034331897@qq.com]
分享 (0)