读书人

建个链表不知道有什么有关问题

发布时间: 2012-03-08 13:30:13 作者: rapoo

建个链表不知道有什么问题
// 链表.cpp : Defines the entry point for the console application.
//

#include "stdafx.h "
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int num;
struct Node *next;
}LNode,*LinkList;
/**************创建链表*****************/
LinkList CreateLink(int n)
{
LNode *head=(LinkList)malloc(sizeof(LNode));
head-> num=n;
head-> next=NULL;
return head;
}
/**************插入链表*****************/
LinkList InsertLink(LinkList head,int position,int variable)
{
int n=1;
LinkList insert_p,find_b,find_p=head;
insert_p=(LinkList)malloc(sizeof(LNode));
insert_p-> num=variable;
while(n <position&&find_p-> next!=NULL)
{
++n;
find_p=find_p-> next;
find_b=find_p;
}
if(find_p-> next==NULL)
{
find_p-> next=insert_p;
insert_p-> next=NULL;
}
else
{
find_p-> next=insert_p;
insert_p-> next=find_b-> next;
}
return head;
}
/**************打印链表*****************/
void print(LinkList head)
{
LinkList print_p=head;
while(print_p-> next!=NULL)
{
cout < <print_p-> num < <endl;
print_p=print_p-> next;
}
}

void main()
{
LinkList head=CreateLink(5);
head=InsertLink(head,1,6);
head=InsertLink(head,2,6);
head=InsertLink(head,2,7);
print(head);
}
如果这样插入就可以:
head=InsertLink(head,1,6);
head=InsertLink(head,2,6);
head=InsertLink(head,3,7);
但这样就不行:
head=InsertLink(head,1,6);
head=InsertLink(head,2,6);
head=InsertLink(head,2,7);

[解决办法]
find_p-> next=insert_p;
insert_p-> next=find_b-> next;
修改为
insert_p-> next=find_p-> next;
find_p-> next=insert_p;

读书人网 >C语言

热点推荐