C語言——順序表和單鏈表的逆置
阿新 • • 發佈:2018-12-08
順序表的逆置
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
typedef struct node {
int num[MAX];
int length;
} *Link, Node;
void reverse(int * num, int length)
{
int i = 0;
int t;
while (i < length / 2) {
t = num[i];
num[i] = num[length - 1];
num[length - 1 ] = t;
length--;
i++;
}
return;
}
int main(void)
{
Link list = (Link)malloc(sizeof(Node));
list->length = 0;
int arrayNum;
while (1 == scanf("%d", &arrayNum)) {
list->num[list->length] = arrayNum;
list->length++;
}
reverse(list ->num, list->length);
for (int i = 0; i < list->length; i++) {
printf("%d ", list->num[i]);
}
putchar('\n');
return 0;
}
單鏈表的逆置
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct node {
struct node * next;
int data ;
}*List, Node;
//逆置函式
void reverse(List head)
{
List p, q;
p = head->next;
head->next = NULL;
while (p) {
q = p;
p = p->next;
q->next = head->next;
head->next = q;
}
}
int main(void)
{
List head = (List)malloc(sizeof(Node));
head->next = NULL;
List prev = head;
int num;
while (1 == scanf("%d", &num)) {
List pnew = (List)malloc(sizeof(Node));
pnew->data = num;
prev->next = pnew;
pnew->next = NULL;
prev = pnew;
}
reverse(head);
List p = head->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
return 0;
}