单链表实现逆置

//单链表逆置

#include <iostream>

#include<stdio.h>

int SIZE = 5;

typedef struct Node

{

int data;

struct Node *next;

}Node, * Hnode;

int main() {

//构建

Node head = NULL;

head = (Node)malloc(sizeof(Node));

Node p = NULL;

Node q = NULL;

p = head;

//输入值
for (int i = 0; i < SIZE;i++) {
q = (Node*)malloc(sizeof(Node));
scanf_s("%d",&q->data);

p->next = q;
p = q;
}
p->next = NULL;//一定要让指针指向NULL (报错)
//逆置
p = head->next;
head->next = NULL;

while (p != NULL) {

q = p;
p = p->next;
q->next = head->next;
head->next = q;

}

p = head->next;
while (p != NULL) {
printf("%d ",p->data);
p = p->next;
}
return 0;

}

 

posted on 2021-12-13 18:34  肆莫耀  阅读(77)  评论(0)    收藏  举报