您的位置:首页 > 理论基础 > 数据结构算法

C 链表的反转(数据结构与算法)

2013-07-06 13:20 190 查看
建立一个链表,然后将其中的元素进行反转。

#include<stdio.h>
#include<stdlib.h>

struct Node
{
int data;
struct Node *next;
};

void display_link(struct Node *head)
{
struct Node *p;
for(p = head; p != NULL; p = p->next) {
printf("%4d",p->data);
}
printf("\n");
}

struct Node * new_link()
{
struct Node *head = NULL, *p1 = NULL ,*p2 = NULL;
int data;
int i = 1;
printf("enter the data:\n");
p1 = (struct Node * )malloc(sizeof(struct Node));
while(1) {
scanf("%d",&p1->data);
if(head == NULL) {
head = p1;
}
p2 = p1;
if(i == 10) {
break;
}
p1 = (struct Node*)malloc(sizeof(struct Node));
p2->next = p1;
i++;
}
p2->next = NULL;

return head;
}

struct Node *transvert_link(struct Node *head)
{
struct Node *p,*p2,*p3;

p = head;
p2 = head->next;
p3 = head->next->next;
while(p3 != NULL) {
p2->next = p;
p = p2;
p2 = p3;
p3 = p3->next;
}
p2->next = p;
head->next = NULL;

return p2;
}

int main(void)
{
struct Node *head;

head = new_link();
printf("\n the data before transvert is:\n");
display_link(head);
head = transvert_link(head);
printf("\n the data after transvert is:\n");
display_link(head);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: