单链表逆序输出
单链表逆序输出
typedef struct node{
int val;
node *next;
}ListNode;
ListNode* reverseList(ListNode *head){
ListNode *cur = head;
ListNode *prev = NULL;
ListNode *temp;
while(cur != NULL){
temp = cur->next;
cur->next = prev;
prev = cur;
cur = temp;
}
return prev;
}
完整代码:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct node{
int val;
node *next;
}ListNode;
ListNode* reverseList(ListNode *head){
ListNode *cur = head;
ListNode *prev = NULL;
ListNode *temp;
while(cur != NULL){
temp = cur->next;
cur->next = prev;
prev = cur;
cur = temp;
}
return prev;
}
int main()
{
int num;
scanf("%d", &num);
ListNode *head ;
ListNode *p, *q;
head = (ListNode *)malloc(sizeof(ListNode));
scanf("%d", &(head->val));
head->next = NULL;
num--;
p = head;
while(num){
q = (ListNode*) malloc(sizeof(ListNode));
scanf("%d", &(q->val));
q ->next = NULL;
p ->next = q;
p = q;
num--;
}
/*
p = head;
while(p!=NULL){
printf("%d ", p->val);
p = p->next;
}
printf("\n");
*/
ListNode *prev;
prev = reverseList(head);
while(prev!=NULL){
printf("%d ", prev->val);
prev = prev->next;
}
printf("\n");
return 0;
}
运行结果: