1.链表逆序
#include <iostream>
using namespace std;
struct node
{
int value;
node * next;
};
node* make_link(void);
node* reverse(node*);
void display(node *);
int main()
{
node *head=make_link();
display(head);
head=reverse(head);
display(head);
return 0;
}
node* make_link(void)
{
node *head=new node();
node *cur=head;
for(int i=0;i<10;i++)
{
cur->value=rand()%10;
cur->next=new node();
cur=cur->next;
}
return head;
}
node* reverse(node *head)
{
node *pre,*post,*cur;
if(!head && !head->next)
return head;
pre=head;
cur=pre->next;
while(cur)
{
post=cur->next;
cur->next=pre;
pre=cur;
cur=post;
}
head->next=NULL;
return pre;
}
void display(node * head)
{
node * cur=head;
while(cur)
{
cout<<cur->value<<" ";
cur=cur->next;
}
cout<<endl;
}
2.链表合并‘
#include <iostream>
using namespace std;
struct node
{
int value;
node *next;
};
node *make_list(void);
void display(node *);
void sort(node *);
node *merge(node *,node *);
int main()
{
node *node1=make_list();
display(node1);
sort(node1);
node *node2=make_list();
display(node2);
sort(node2);
node *mnode=merge(node1,node2);
display(mnode);
return 0;
}
node *make_list(void)
{
node *head=new node();
node *cur=head;
for(int i=0;i<10;i++)
{
cur->value=rand()%10;
cur->next=new node();
cur=cur->next;
}
return head;
}
void display(node *head)
{
node *cur=head;
while(cur)
{
cout<<cur->value<<" ";
cur=cur->next;
}
cout<<endl;
}
void sort(node *head)
{
node *cur=head;
while(cur)
{
node *min=cur;
node *cur2=cur->next;
while(cur2)
{
if(cur2->value < min->value)
min=cur2;
cur2=cur2->next;
}
int temp=cur->value;
cur->value=min->value;
min->value=temp;
cur=cur->next;
}
}
node *merge(node *h1,node *h2)
{
node *mcur=new node();
node *cur1=h1;
node *cur2=h2;
while(cur1&&cur2)
{
if(cur1->value < cur2->value)
{
mcur->next=cur1;
mcur=mcur->next;
cur1=cur1->next;
}
else
{
mcur->next=cur2;
mcur=mcur->next;
cur2=cur2->next;
}
}
if(cur1)
mcur->next=cur1;
else
mcur->next=cur2;
return h1->value < h2->value ? h1:h2;
}
3.一组人(7个),围成一圈,从某人开始数到第3个的人出列,再接着从下一个人开始数,依次输出出列的人。(报数:共n个人 从1编号,设从第s个人报号,报到m出队,依次输出出队的人。
//方法1:链表法
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct Node
{
int data;
struct Node *next;
}LinkList;
LinkList *create(int n)
{
LinkList *p,*q,*head;
int i=1;
p=(LinkList*)malloc(sizeof(LinkList));
p->data=i;
head=p;
for(i=1;i<=n;i++)
{
q=(LinkList*)malloc(sizeof(LinkList));
q->data=i+1;
p->next=q;
p=q;
}
p->next=head; //使链表尾连接链表头,形成循环链表
return head;
free(p);
p=NULL;
free(q);
q=NULL;
}
void deletefun(LinkList *L,int m)
{
LinkList *p,*q,*temp;
int i;
p=L;
while(p->next!=p)
{
for(i=1;i<m;i++)
{
q=p;
p=p->next;
}
printf("%5d",p->data);
temp=p;
q->next=p->next;
p=p->next;
free(temp);
}
printf("%5d\n",p->data);
}
int main()
{
int n=7,m=3;//此时n=7,m=3
LinkList *head1;
head1=create(n);
deletefun(head1,m);
return 0;
}