码迷,mamicode.com
首页 > 编程语言 > 详细

c语言链表翻转

时间:2015-03-27 22:02:59      阅读:375      评论:0      收藏:0      [点我收藏+]

标签:

明天多益网络一面,晚上写了个简单的链表翻转程序找找感觉,两种思路实现。一种通过头插法实现翻转,另一种则是通过更改节点指针指向来实现。虽然简单,但动动手,活跃下思维!希望明天面试顺利!

#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;
}

c语言链表翻转

标签:

原文地址:http://www.cnblogs.com/wtuhan/p/4372945.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!