单链表操做

// list.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<conio.h>
using namespace std;
struct ListNode
{
  int data;
  ListNode *next;
};
//创建单链表
ListNode *creat()
{
  ListNode *head,*p,*s;
  int x,cycle=1;
  head=(ListNode*)malloc(sizeof(ListNode));
  p=head;
  cout<<"请输入单链表的数据,以0做为结束标识:"<<endl;
  while(cycle)
  { 
    cin>>x;
    if(x!=0)//以0为标识
    {
      s=(ListNode *)malloc(sizeof(ListNode));
      s->data=x;
      p->next=s;
      p=s;
    }
    else cycle=0;
  }
  head=head->next;
  p->next=NULL;
  cout<<endl;
  return (head);
}
 //求单链表的长度
int length(ListNode *head)
{
  int n=0;
  ListNode *p;
  p=head;
  while(p!=NULL)
  {
    p=p->next;
    n++;
  }
  return(n);
}
//输出单链表
void print(ListNode *head)
{
  ListNode *p;int n;
  n=length(head);
  cout<<"如今,长度为"<<n<<"的单链表更新为:"<<endl;
  p=head;
  if(head!=NULL)
  {
    while(p!=NULL)
    {
      cout<<p->data<<'\t';
      p=p->next;
    }
  }
  printf("\n");
}
//删除单链表中的某个元素
ListNode *del(ListNode *head,int num)
{
  ListNode *p1,*p2;
  p1=head;
  while(num!=p1->data&&p1->next!=NULL)
  {
    p2=p1;
    p1=p1->next;
  }
  if(num==p1->data)
  {
    if(p1==head)
    {
      head=p1->next;
      free(p1);
    }
    else
      p2->next=p1->next;
  }
  else
    cout<<num<<"没有在单链表中找到!"<<endl;//printf("\n%d 没有在单链表中找到!",num);
  return head;
}
//在单链表中插入一个元素
ListNode *insert(ListNode *head,int num)
{
  ListNode *p0,*p1,*p2;
  p1=head;
  p0=(ListNode *)malloc(sizeof(ListNode));
  p0->data=num;
  while(p0->data>p1->data&&p1->next!=NULL)
  {
    p2=p1;p1=p1->next;
  }
  if(p0->data<=p1->data)
  {
    if(head==p1)
    {
      p0->next=p1;
      head=p0;
    }
    else
    {
      p2->next=p0;
      p0->next=p1;
    }
  }
  else
  {
    p1->next=p0;
    p0->next=NULL;
  }
  return head;
}
//对单链表从小到大排序:
ListNode *sort(ListNode *head)
{
  ListNode *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;
}
//对单链表进行逆置
ListNode *reverse(ListNode *head)
{
  ListNode *p1,*p2,*p3;
  
  if(head==NULL||head->next==NULL)
    return head;
  p1=head,p2=p1->next;
  while(p2)
  {
    p3=p2->next;
    p2->next=p1;
    p1=p2;
    p2=p3;
  }
  head->next=NULL;
  head=p1;
  return head;
}
int main()
{
  ListNode *head;
  int n,del_num,insert_num;
  head=creat();
  print(head);
  cout<<"\n请对单链表排序:";
  head=sort(head);
  print(head);
  cout<<"\n请输入单链表中要删除的数据: ";
  cin>>del_num;
  head=del(head,del_num);
  print(head);
  cout<<"\n请输入单链表中要插入的数据:";
  cin>>insert_num;
  head=insert(head,insert_num);
  print(head);
  cout<<"\n请对单链表进行逆置:";
  head=reverse(head);
  print(head);
  system("pause");
  return 0;
}
相关文章
相关标签/搜索