最近在学习mooc网上的 陈越、何钦铭 老师的数据结构,在做作业的时候遇到单链表反转问题,于是就拉出来单独了解一下:
方法一:用数组下标模拟内存地址,代码如下:
#include <stdio.h>
struct Node{
int value;
int position;
int next=-1;
};
typedef struct Node item;
item item_list[100010];
void ReadLink(int head_node)
{
while(head_node!=-1)
{
printf("%05d %d %05d \n",item_list[head_node].position, item_list[head_node].value, item_list[head_node].next);
head_node = item_list[head_node].next;
}
printf("\n");
}
int main() {
int head_position, node_num, next_position, value, position, tmp;
scanf("%d %d", &head_position, &node_num);
for (int i = 0; i < node_num; ++i) {
scanf("%d %d %d", &position, &value, &next_position);
item_list[position].position = position;
item_list[position].value = value;
item_list[position].next = next_position;
}
printf("反转前:\n");
ReadLink(head_position);
int front, rear, p;
front = item_list[head_position].position;
rear = item_list[item_list[head_position].next].position;
while(rear!=-1) {
p = item_list[rear].next;
item_list[rear].next = item_list[front].position;
front = rear;
rear = p;
}
item_list[head_position].next = -1;
printf("反转后:\n");
ReadLink(front);
}
输出:
反转前:
00100 1 12309
12309 2 33218
33218 3 00000
00000 4 99999
99999 5 68237
68237 6 -0001
反转后:
68237 6 99999
99999 5 00000
00000 4 33218
33218 3 12309
12309 2 00100
00100 1 -0001
方法二:用指针操作单链表:
#include <stdio.h>
#include<stdlib.h>
typedef struct Node* ptrNode;
struct Node{
int val;
ptrNode next;
};
void ReadLink(ptrNode front)
{
while(front!=NULL){
printf("%d ", front->val);
front = front->next;
}
printf("\n");
}
int main()
{
int node_num, val;
ptrNode front, rear;
rear = (ptrNode)malloc(sizeof(struct Node));
rear->next = NULL;
front = rear;
scanf("%d", &node_num);
for (int i = 0; i < node_num; ++i) {
scanf("%d", &val);
ptrNode p = (ptrNode)malloc(sizeof(struct Node));
p->val = val;
p->next = NULL;
rear->next = p;
rear = p;
}
ptrNode p;
printf("反转前:\n");
ReadLink(front->next);
front = front->next;
rear = front->next;
front->next = NULL;
while(p!=NULL){
p = rear->next;
rear->next = front;
front = rear;
rear = p;
}
free(p);
printf("反转后:\n");
ReadLink(front);
}
输出
5
2 4 6 8 10
反转前:
2 4 6 8 10
反转后:
10 8 6 4 2