Cチェーンテーブルの反転(データ構造とアルゴリズム)
1316 ワード
チェーンテーブルを作成し、要素を反転します.
#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("
");
}
struct Node * new_link()
{
struct Node *head = NULL, *p1 = NULL ,*p2 = NULL;
int data;
int i = 1;
printf("enter the data:
");
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("
the data before transvert is:
");
display_link(head);
head = transvert_link(head);
printf("
the data after transvert is:
");
display_link(head);
return 0;
}