一则面试题:写一个方法,讲一个单向链表逆序。
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}Node;
//创建链表
Node *creat(int n) //n为节点个数
{
Node *head, *p, *s;
int i;
p = head = (Node *)malloc(sizeof(Node));
for(i = 1;i <= n;i++)
{
s = (Node *)malloc(sizeof(Node));
scanf("%d", &s->data);
p->next = s;
p = s;
}
p->next = NULL;
return head;
}
//原地置换
void reverse(Node *head)
{
Node *p,*s,*t;
p = head;
s = p->next;
//主要置换过程
while(s->next != NULL)
{
t = s->next;
s->next = p;
p = s;
s = t;
}
s->next = p;
head->next->next = NULL; //收尾
head->next = s; //赋头
}
//显示链表内容
void display(Node *head)
{
Node *p;
p = head->next;
while(p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
int main()
{
int n;
Node *head;
printf("请输入链表节点数:");
scanf("%d",&n);
head = creat(n);
printf("原链表:\n");
display(head);
reverse(head);
printf("置换后链表:\n");
display(head);
}
运行:
请输入链表节点数:5
11 22 33 44 55
原链表:
11 22 33 44 55
置换后链表:
55 44 33 22 11