创建单链表输入单链表的数据元素以-1结束。利用原有结点实现单链表的就地逆置输出逆置后的单链表。typedef struct LNodeint data;struct LNode next;LNode LinkList;【输入形式】1 2 3 4 5 6 7 8 9 10 -1【输出形式】10 9 8 7 6 5 4 3 2 1
#include <stdio.h> #include <stdlib.h>
typedef struct LNode{ int data; struct LNode *next; }LNode, *LinkList;
int main() { LinkList L = (LNode*)malloc(sizeof(LNode)); //创建头结点 L->next = NULL; //初始为空链表
int num;
scanf("%d", &num);
while (num != -1) {
LNode *newNode = (LNode*)malloc(sizeof(LNode));
newNode->data = num;
newNode->next = L->next;
L->next = newNode;
scanf("%d", &num);
}
//就地逆置
LNode *p, *q;
if (L->next != NULL) {
p = L->next;
q = p->next;
p->next = NULL;
while (q != NULL) {
LNode *temp = q->next;
q->next = p;
p = q;
q = temp;
}
L->next = p;
}
//输出逆置后的单链表
LNode *cur = L->next;
while (cur != NULL) {
printf("%d ", cur->data);
cur = cur->next;
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/bIgO 著作权归作者所有。请勿转载和采集!