西安电子科技大学数据结构与算法上机实验——单链表逆置
先通过一次遍历所有结点,判断其个数值,进而得到中间结点的位置,定义两个工作指针一个从前向后开始移动,另一个从最后像前面逆向移动,移动的过程中进行循环交换中间结点对称两侧的节点数值,不改变原结点的连接情况
#include<malloc.h>
#include<stdio.h>
# define LEN sizeof(struct linklist)
struct linklist {
int num;
struct linklist *next;
};
struct linklist *create();
void print(struct linklist *);
void invert(struct linklist *);
int main(void) {
struct linklist *head;
printf("***************请创建链表*****************\n");
head = create();
printf("***************输出原链表*****************\n");
print(head);
invert(head);//调用单链表逆置的函数
printf("************输出逆置后的链表**************\n");
print(head);
return 0;
}
struct linklist *create() {
struct linklist *p, *q, *head = NULL;
p = q = (struct linklist *) malloc(LEN);
scanf("%d", &p->num);
while (p->num != 0) {
if (head == NULL) {
head = p;
} else {
q->next = p;
}
q = p;
p = (struct linklist *) malloc(LEN);
scanf("%d", &p->num);
}
q->next = 0;
free(p);
return head;
}
void print(struct linklist *const head) {
struct linklist *p = head;
do {
printf("%d ", p->num);
p = p->next;
} while (p != NULL);
printf("\n");
}
void invert(struct linklist *const head) {
int i, j, t, m, n = 0;
struct linklist *p = head, *q;
while (p != NULL) {
p = p->next;
n++;
}
p = head;
m = n / 2;
for (i = 0; i < m; i++) {
q = head;
for (j = 0; j < n - 1; j++) {
q = q->next;
}
t = p->num;
p->num = q->num;
q->num = t;
p = p->next;
n--;
}
}