1.交换一个单链表的首尾。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
int value;
struct node *next;
}NODE;
NODE *swtch(NODE *h)
{
NODE *head = h,*tailpre = h,*tmp;
if(!head)
return NULL;
//拿到末尾的和末尾前一个node,使前一个指向head,使末尾的指向head,使head指向null
while(tailpre->next->next)
tailpre = tailpre ->next;
tmp = tailpre->next;
tmp->next = head->next;
tailpre->next = head;
head->next = NULL;
head = tmp;
return head;
}
int main(void)
{
NODE a,b,c,d,e,f,*head,*p;
a.value = 1;
b.value = 2;
c.value = 3;
d.value = 4;
e.value = 5;
f.value = 6;
head = &a;
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
e.next = &f;
f.next = NULL;
p = head;
do
{
printf("%d\n",p->value);
p = p->next;
}while(p != NULL);
printf("************************\n");
p = swtch(head);
do
{
printf("%d\n",p->value);
p = p->next;
}while(p != NULL);
return 0;
}
结果:
1
2
3
4
5
6
************************
6
2
3
4
5
1