您的位置:首页 > 其它

关于单链表

2015-12-01 21:30 260 查看
//单链表结构体
typedef struct student
{
int data;
struct student *next;
}node;

//建立单链表
node *create()
{
node *head,*p,*s;
int x,cycle=1;
head=(node*)malloc(sizeof(node)); //建立头节点

printf("创建中,输入data:");
scanf("%d",&x);//设立头结点
if (x == 0)
{
head = NULL;
return head;
}
else
{
head->data = x;
}
p=head;
while(cycle)
{
printf("\n创建中,输入data:");
scanf("%d",&x);
if(x!=0)
{
s=(node*)malloc(sizeof(node));//每次新建一个节点
s->data=x;
printf("\n%d",s->data);
p->next=s;
p=s;
}
else
{
cycle=0;
}
}
//head=head->next;
p->next=NULL;
//printf("\n   yyy   %d",head->data);
return (head);
}
//单链表测长
int length(node *head)
{
int n=0;
node *p;
if (head == NULL)
{
return n;
}
p=head;//把头结点算上
while(p!=NULL)
{
p=p->next;
n++;
}
return (n);
}
//单链表打印
void print(node *head)
{
node *p;
int n;
n=length(head);
printf("\n链表长度:%d",n);
p=head;
if(head==NULL)
return;
printf("\n链表内容:\n",n);
while(p!=NULL)
{
printf("data:%d\n",p->data);
p=p->next;
}
}
//删除第一个值为num的节点
node* del(node* head,int num)
{
node *p1,*p2;
cout<<endl<<"删除"<<num<<endl;
if (head ==NULL)
{
cout<<"链表为空"<<endl;
return head;
}
p2 = head;
p1 = head;
while (p1->data != num && p1->next != NULL)
{
p2 = p1;
p1 = p1->next;
}
if (p1->data == num)
{
if (p1 == head)
{
head = p1->next;
free(p1);
}
else
{
p2->next = p1->next;
free(p1);
}
}
else
{
cout<<"找不到该值"<<endl;
}
return head;
}
//按照num的大小,插入一个节点
node* insert(node* head,int num)
{
node* p0,*p1,*p2;//p0是要插入的节点
p0 = (node*)malloc(sizeof(node));
p0->data = num;
p1 = head;
while(p0->data > p1->data && p1->next)
{
p2 = p1;
p1 = p1->next;
}
if(p0->data <= p1->data)
{
//头部(最小的值)
if (p1 == head)
{
p0->next = head;
head = p0;
}
else
{
p0->next = p1;
p2->next = p0;
}
}
//尾部(最大的值)
else
{
p1->next = p0;
p0->next = NULL;
}
return head;
}
//排序
node* sort(node* head)
{
node *p;
int n;
int temp;
n = length(head);
if (head == NULL || head->next == NULL)
{
return head;
}
p = head;
for (int j = 1;j<n;j++)
{
p = head;
for (int i = 0;i<n-j;i++)
{
if (p->data > p->next->data)
{
temp = p->data;
p->data = p->next->data;
p->next->data = temp;
}
p = p->next;
}
}
return head;
}
//逆置
node* reverse(node* head)
{
node *p1,*p2,*p3;
if (head == NULL || head->next == NULL)
{
return head;
}
p1 = head;
p2 = head->next;
while (p2)
{
p3 = p2->next;
p2->next = p1;
p1 = p2;
p2 = p3;
}
head->next = NULL;
head = p1;
return head;
}
int _tmain(int argc, _TCHAR* argv[])
{
node *p = create();
cout<<"创建后"<<endl;
print(p);
//删除第一个值为4的节点
p = del(p,4);
cout<<"删除'4'后"<<endl;
print(p);
//插入值为7的节点
p = insert(p,7);
cout<<"插入‘7’后"<<endl;
print(p);
cout<<"排序后"<<endl;
p = sort(p);
print(p);
cout<<"逆置后"<<endl;
p = reverse(p);
print(p);

getchar();
return 0;
}
单链表有2种,一种是没有头结点的,一种有,head里的数据域是有值的,上面就是。

参考的网址(当然它们也有错误)

[C++面试题]之单链表 - it笨笨 - 博客园

http://blog.csdn.net/xyx19890816/article/details/5952502

C语言单向链表的建立

链表百度百科

链表,头指针,头结点
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: