Chinaunix首页 | 论坛 | 博客
  • 博客访问: 17063
  • 博文数量: 5
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 55
  • 用 户 组: 普通用户
  • 注册时间: 2013-02-15 11:38
文章分类

全部博文(5)

文章存档

2013年(5)

我的朋友

分类: C/C++

2013-04-18 14:57:36

#include
#include
#include
typedef int TYPE;
typedef struct Link
{
 TYPE data;
 struct Link *next; 
}Node;
Node* Link_init(Node *head)//含有头结点的链表
{
 head=(Node*)malloc(sizeof(Node));
 assert(head!=NULL);
 head->next=NULL;
 return head;
}
Node *Link_create(Node *head)//尾插法
{
 Node *p,*q;
 p=head;
 TYPE mydata;
 while(1)
 {
  scanf("%d",&mydata);
  if(mydata==-1)
  {
   break;
  }
  q=(Node*)malloc(sizeof(Node));
  q->data=mydata;
  q->next=p->next;
  p->next=q;
  p=q;
 }
 return head;
}
int Link_search(Node *head,TYPE x)
{
 Node *p;
 p=head->next;
 int index=0;
 while((p!=NULL)&&(p->data!=x))
 {
  p=p->next;
  index++;
 }
 if(p==NULL)
 {
  return -1;
 }
 else
 {
  return index;
 }
}
void Link_insert(Node *head,int i,int x)
{
 Node *p,*q;
 p=head;
 int j=0;
 for(j=0;j
 {
  p=p->next;
 }//找到第i个位置的前一个节点 (包括第0个位置)
 q=(Node*)malloc(sizeof(Node));
 assert(q!=NULL);
 q->data=x;
 q->next=p->next;
 p->next=q;
}
void Link_delete(Node *head,int i)
{
 Node *p,*q;
 p=head;
 int j=0;
 for(j=0;j
 {
  p=p->next;
 }
 q=p->next;
 p->next=q->next;
 free(q);
}
void Link_reverse(Node *head)
{
 Node *p=head->next;
 Node *pre=head->next;
 Node *pnext;
 Node *cur=p->next;
 while(cur!=NULL)
 {
  pnext=cur->next;
  cur->next=pre;
  pre=cur;
  cur=pnext;
 }
 p->next=NULL;
 head->next=pre;
}
void Link_display(Node *head)
{
 Node *p;
 p=head->next;
 while(p!=NULL)
 {
  printf("%d  ",p->data);
  p=p->next;
 }
 printf("\n");
}
int main(void)
{
 Node *head;
 head=Link_init(head);
 head=Link_create(head);
 Link_display(head);
 int chose=0;
 int index=0;
 while(1)
 {
  printf("please:");
  scanf("%d",&chose);
  if(chose!=-1)
  {
   switch(chose)
   {
    case 1:
    
    Link_insert(head,3,8);
    break;
    case 2:
    index=Link_search(head,1);
    printf("%d \n",index);
    break;
    case 3:
    Link_delete(head,1);
    break;
    case 4:
    Link_display(head);
    break;
    case 5:
    Link_reverse(head);
    break;
    default:
    printf("error");
    break;
   }
 
  } 
 }
 return 0;
}
阅读(1070) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~