单链表的创建
带头结点不带头结点
代码示例
using namespace std;
struct ListNode{
int val;
ListNode
*next;
};
//带头节点的创建
ListNode * CreatelistisNode(ListNode
*L)
{
if(L==NULL)
{
ListNode
*head=new ListNode;
head->
next=NULL;
L=head;
}
ListNode
*p=L;
int n;
printf(
"请输入要创建的单链表的长度:");
scanf(
"%d",&n);
for(
int i=
0;i<n;i++)
{
int number;
printf(
"请输入第%d个值:",i+
1);
scanf(
"%d",&number);
ListNode
*newnode=new ListNode;
newnode->val=number;
newnode->
next=NULL;
p->
next=newnode;
p=newnode;
}
return L;
}
//不带头节点的创建
ListNode* CreateListNode(ListNode
*head)
{
ListNode
*p=head;
int n;
printf(
"请输入要创建的单链表的长度:");
scanf(
"%d",&n);
for(
int i=
0; i<n; i++)
{
int number;
printf(
"请输入第%d个值:",i+
1);
scanf(
"%d",&number);
if(p==NULL)
{
ListNode
*s = new ListNode;
//定义一个
s节点用来存放每次要输入的值
s->val = number;
s->
next = NULL;
head=
s;
p=
s;
}
else
{
ListNode
*s = new ListNode;
//定义一个
s节点用来存放每次要输入的值
s->val = number;
s->
next = NULL;
p->
next =
s;
p =
s;
}
}
return head;
}
void prinfout(ListNode
*L)
{
ListNode
*p=L;
while(p!=NULL)
{
printf(
"%d ",p->val);
p=p->
next;
}
}
int main()
{
ListNode
*L=NULL;
ListNode
*p1=CreateListNode(L);
prinfout(p1);
cout<<endl;
ListNode
*p2=CreatelistisNode(L);
prinfout(p2->
next);
return 0;
}
小结:在创建链表时要考虑传入的指针是否为空,然后分情况讨论。