#include<stdio.h>

struct Node { int data; struct Node* next; };

void reverseList(struct Node** head_ref) { struct Node* prev = NULL; struct Node* current = head_ref; struct Node next = NULL; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *head_ref = prev; }

void printList(struct Node* node) { while (node != NULL) { printf("%d ", node->data); node = node->next; } }

int main() { struct Node* head = NULL; struct Node* second = NULL; struct Node* third = NULL;

head = (struct Node*)malloc(sizeof(struct Node)); 
second = (struct Node*)malloc(sizeof(struct Node)); 
third = (struct Node*)malloc(sizeof(struct Node)); 

head->data = 1; 
head->next = second; 

second->data = 2; 
second->next = third; 

third->data = 3; 
third->next = NULL; 

printf("Original List:\n"); 
printList(head); 

reverseList(&head); 

printf("\nReversed List:\n"); 
printList(head); 

return 0; 

}

/* 输入: 无 输出: Original List: 1 2 3 Reversed List: 3 2 1 *

用c原因完成一段代码要求有输入和输出利用单链表原来的节点空间逆转一个单链表

原文地址: http://www.cveoy.top/t/topic/fbl5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录