|
下面是一个单向链表的逆序操作,希望对你有帮助:
[code:1]
/*****************************************************************
* code by [email protected]
* date 2005-09-02
* description: 单向链表逆序演示
*****************************************************************/
#include <stdlib.h>
#include <stdio.h>
struct node {
int data;
struct node *next;
};
struct node *reverselist(struct node *h);
void printnode(struct node *h);
int main()
{
struct node *head;
struct node *p;
static int a[5] = {7,6,5,4,3};
int i;
head = (struct node *)malloc(sizeof(head)*5);
p = head;
/* 构造链表*/
for(i = 0; i <5; i++) {
p->data = a[i];
if (i != 4)
p->next = p + sizeof(p);
else
p->next = NULL;
p = p->next;
}
printf("Before Reverse\n");
printnode(head);
printf("After Reverse\n");
printnode(reverselist(head));
return 0;
}
/* 链表逆序 */
struct node *reverselist(struct node *h)
{
struct node *p;
struct node *tmp;
p = h; /* 两条链表*/
p = p->next;
h->next = NULL; /* 原来的头结点作为尾结点 */
tmp = h;
while(p) {
h = p;
p = p->next;
h->next = tmp;
tmp = h;
}
return h;
}
/* 打印链表 */
void printnode(struct node *h)
{
while(h) {
printf("%d ", h->data);
h = h->next;
}
printf("\nEND\n");
}
[/code:1]
以下是运行结果:
[code:1]
Before Reverse
7 6 5 4 3
END
After Reverse
3 4 5 6 7
END
[/code:1] |
|