创建链表时需要主要的几点
1、插入创建链表时应该传递指向表头的指针的指针,因为插入的值有可能放在链表的最前面,形成新的表头。
2、单链表逆序,其实是把一个链表分成两段进行的。取出表头,使其指向下一个结点的指针为null。此时原链表中的第二个结点成为了原链表中的头结点。然后取出第二个结点,依次进行。到最后的时候需要修改单链表最后的一个节点变成表头,这样就完成了单链表逆序。
代码如下
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
typedef struct _list
{
int value;
struct _list *next;
}mylist,*plist;
bool insert2list(plist *pl,int value)
{
plist previous=NULL;
plist current=*pl;
while((current!=NULL)&&(value<current->value))
{
previous=current;
current=current->next;
}
//新建节点
plist ptemp=(plist)malloc(sizeof(mylist));
ptemp->value=value;
ptemp->next=current;
//插入为头结点的情况
if (previous==NULL)
{
(*pl)=ptemp;
}
else
previous->next=ptemp;
return true;
}
void ouput_list(plist pl)
{
while(pl->next!=NULL){
printf("%d\n",pl->value);
pl=pl->next;
}
printf("%d\n",pl->value);
}
//链表逆序
int reserve_list(plist *pl)
{
plist phead=*pl,psec_head=NULL;
if ((phead->next==NULL)||(phead->next->next==NULL))
{
return 0;//表示只有一个节点的链表或者是空链表
}
psec_head=phead->next;//临时指针
plist pnew=phead;//头结点的处理
pnew->next=NULL;
while(psec_head->next!=NULL)
{
phead=psec_head;
psec_head=psec_head->next;
phead->next=pnew;
pnew=phead;
}
psec_head->next=phead;//尾节点的处理
*pl=psec_head;
return 1;
}
int creat_list()
{
plist pfirst=(plist)malloc(sizeof(mylist));
pfirst->next=NULL;
pfirst->value=0;
for (int i=1;i<5;i++)
{
insert2list(&pfirst,i);
}
ouput_list(pfirst);
reserve_list(&pfirst);
ouput_list(pfirst);
return 1;
}
int main()
{
creat_list();
return 1;
}