明天多益网络一面,晚上写了个简单的链表翻转程序找找感觉,两种思路实现。一种通过头插法实现翻转,另一种则是通过更改节点指针指向来实现。虽然简单,但动动手,活跃下思维!希望明天面试顺利!
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}Node;
Node *CreateLinkList();
void PrintLinkList(Node *h);
void Traverse1(Node *h);
void Traverse2(Node *h);
int main()
{
Node * H = CreateLinkList();
Traverse1(H);
PrintLinkList(H);
Traverse2(H);
PrintLinkList(H);
return 0;
}
void Traverse2(Node *h)
{
Node *start = h->next;
Node *pre = start->next;
Node *cur = pre;
start->next = NULL;
while(pre)
{
pre = pre->next;
cur->next = start;
start = cur;
cur = pre;
}
h->next = start;
}
void Traverse1(Node *h)
{
Node* cur = h->next;
Node *pre = cur->next;
cur->next = NULL;
Node *p = NULL;
while(pre)
{
p = pre;
pre= pre->next;
h->next = p;
p->next = cur;
cur = p ;
}
}
void PrintLinkList(Node *h)
{
Node *list = h->next;
while(list)
{
printf("%d\n",list->data);
list = list->next;
}
}
Node *CreateLinkList()
{
Node *h = (Node *)malloc(sizeof(Node));
h->data = 0;
h->next = NULL;
Node *cur = h;
printf("请依次输入节点数值:(-1结束)\n");
int v;
do
{
scanf("%d",&v);
Node * newNode = (Node *)malloc(sizeof(Node));
newNode->data = v;
cur->next = newNode;
newNode->next = NULL;
cur= newNode;
}while(v != -1);
return h;
}