这几天看欧立奇的《程序员面试宝典》,发现其中单链表的建立的程序存在错误,特别改正如下,原书的程序求的链表的长度要比正确的单链表的长度要多1。
在写程序时候,要特别注意if和while的区别。
下面的程序是单链表的建立、插入、删除、逆序、排序、测长等程序代码,全部都调试通过(存在的问题在于,将链表的头指针看成了一个结点)。
#include <iostream>
using namespace std;
#include<malloc.h>
#define LEN sizeof(struct student)
typedef struct student
{
int data;
struct student *next;
}node;
struct student *creat()
{
int data;
int cycle =1;
int n=0;
struct student *head, *p_old, *p_new;
p_old =(struct student *)malloc(LEN);
while(cycle == 1)
{
printf("Please input the data \n");
scanf("%d",&data);
if(data != 0)
{
n=n+1;
if (n==1)
{
head =p_old;
p_old ->data =data;
p_old ->next =NULL;
}
else
{
p_new=(struct student*)malloc(LEN);
p_new ->data =data;
p_old -> next =p_new;
p_old = p_new;
}
}
else
{
cycle = 0;
}
}
//head=head->next;
p_old ->next =NULL;
int b= head->next->next->data;
return head;
}
int length(struct student *head)
{
struct student *p_start;
int num =0;
p_start=head;
while (p_start !=NULL)
{
num++;
p_start=p_start ->next;
}
return num;
}
void print(struct student *head)
{
struct student *p_start;
int n=length(head);
p_start =head;
for(int i=0;i<n;i++)
{
cout<<p_start->data<<" ";
p_start =p_start->next;
}
cout<<endl; //endl
}
node *del(struct student *head,int num)
{
node *p_front;
node *p_behind;
p_front=head;
//如果没有达到需要删除的数据,就继续移动指针指向,否则,进入下一段落
//的if判断
while(p_front->data != num && p_front->next !=NULL)
{
p_behind=p_front;
p_front=p_front->next;
}
if (p_front->data==num)
{
if (p_front==head)
{
head = p_front->next;
free(p_front);
}
else
{
p_behind->next = p_front->next;
free(p_front);
}
}
return head;
}
node *insert(node *head,int num)
{
node *p_behind,*p_front,*p_new;
p_front = head;
p_new = (node *)malloc(LEN);
p_new->data = num;
while(p_front->data < num && p_front->next != NULL)
{
p_behind = p_front;
p_front = p_front->next;
}
if(p_front->data >= num)
{
if(p_front==head)
{
p_new->next = p_front;
head = p_new;
}
else if(p_front != head && p_front->next != NULL)
{
p_behind->next =p_new;
p_new->next = p_front;
}
}
else
{
p_front->next = p_new;
p_new->next = NULL;
}
return head;
}
node *sort(node *head)
{
node *p;
int n;
if(head==NULL || head->next ==NULL)
{
return head;
}
n=length(head);
int temp;
for(int i=1;i<n;i++)
{
p=head;
for(int j=0;j<n-i;j++)
{
if(p->data < p->next->data)
{
temp =p->next->data;
p->next->data =p->data;
p->data=temp;
}
p=p->next;
}
}
return head;
}
node *reverse(node *head)
{
node *p,*q,*r;
p=head;
q=p->next;
while(q != NULL)
{
r =q->next;
q->next = p;
p = q;
q =r;
}
head ->next;
head = p;
return head;
}
void main()
{
struct student *head;
int len;
int num = 12;
head =(struct student *)malloc(sizeof( struct student));
head = creat();
len = length(head);
print(head);
head = insert(head,20);
print(head);
head =sort(head);
print(head);
head =reverse(head);
int b=head->next->data;
}