今天微软电面...有一个题目是将链表反转,返回头结点...差点嗝屁..于是把链表纠结了一下...
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct st
{
int data;
struct st *next;
};
//reverse list
struct st *reverse(struct st *head)
{
struct st *p=head->next,*q;
struct st *Head;
q=p->next;
p->next=NULL;
Head=p;
p=q;
while(p!=NULL)
{
q=p->next;
p->next=Head;
Head=p;
p=q;
}
head->next=Head;
return head;
}
//insert list
void Insert(struct st *head,int x, int i)
{
struct st *p=head->next,*q=head;
i--;
while(i--)
{
q=p;
p=p->next;
}
struct st *now = (struct st*)malloc(sizeof(struct st));//
now->data=x;
now->next=p;
q->next=now;
}
//delete list
void Delete(struct st *head, int x)
{
struct st *p=head->next,*q=head;
while(p!=NULL)
{
if(p->data==x)
{
q->next=p->next;
}
q=p;
p=p->next;
}
}
int main()
{
int n,m,i,j;
struct st head;
head.next=NULL;
for(i=1;i<=8;i++)
{
insert(&head,i,i);
}
struct st *Head=reverse(&head);
struct st *p=Head->next;
while(p!=NULL)
{
printf("%d\n",p->data);
p=p->next;
}
Insert(&head,10,1);
Delete(&head,4);
Delete(&head,10);
Delete(&head,8);
p=Head->next;
while(p!=NULL)
{
printf("%d\n",p->data);
p=p->next;
}
return 0;
}
posted on 2010-07-22 21:55
ccyy 阅读(111)
评论(0) 编辑 收藏 引用