程序有问题,需改进。
#include <iostream>
using namespace std;
typedef struct NODE{
int data;
NODE *next;
}node;
//create a list.
node *create()
{
node *head, *first, *second;
head = new(node);
first = head;
int num;
cout << "Now input the list:\n";
while(cin >> num && num)
{
cout << "number:" << num << endl;
second = new(node);
second->data = num;
first->next = second;
second->next = NULL;
first = second;
}
if(first - head == 0)
return NULL;
head = head->next;
return head;
}
//打印链表.
void printList(node *head)
{
cout << "Now output the list:\n";
//list is null.
if(head == NULL)
return ;
//list is not null.
else
{
node *p = head;
while(p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
}
//删除节点.
node *deleteNode(node *head, int num)
{
node *first, *second;
first = head;
while(num != first->data && first->next != NULL)
{
second = first;
first = first->next;
}
//---找到了要删除的节点.
if(num == first->data)
{
//头结点.
if(first == head)
head = head->next;
//不是头结点.
else
second->next = first->next;
free(first);
}
//---没有找到要删除的节点.
else
cout << "can not find the node!\n";
return head;
}
//插入节点.
node *insertNode(node *head,int num)
{
node *newNode = new(node);
newNode->data = num;
node *first = head, *second;
while(num > first->data && first->next != NULL)
{
second = first;
first = first->next;
}
//---未达到链表结尾,即在链表头部或内部插入节点.
if(num <= first->data)
{
//插入头结点之前.
if(first == head)
{
newNode->next = head;
head = newNode;
}
//插入头结点之后.
else
{
newNode->next = first;
second->next = newNode;
}
}
//---达到链表结尾,即在链表尾部插入.
else
{
first->next = newNode;
newNode->next = NULL;//注意将为节点的指针置为空.
}
return head;
}
//求链表长度.
int len(node *head)
{
int cnt = 0;
node *index = head;
while(index != NULL)
{
cnt++;
index = index->next;
}
return cnt;
}
//单链表排序.
node *sort(node *head)
{
if(head == NULL || head->next == NULL)
return NULL;
node *first = head;
node *second = head->next;
int n = len(head);cout << "the lenth is: " << len(head) << endl << endl;
int temp;
for(int i = 1;i < n;i++)
{
//第i趟比较.
for(int j = 1;j < n-i;j++ )
{
if(first->data > second->data)
{
temp = first->data;
first->data = second->data;
second->data = temp;
}
first = first->next;
second = second->next;
}
}
return head;
}
int main()
{
node *p = create();cout << endl << "*p:" << *p->data << endl;
printList(p);
p = deleteNode(p,5);
printList(p);
p = sort(p);
printList(p);
p = insertNode(p,8);
printList(p);
return 0;
}