【程序73】
题目:反向输出一个链表。
1.程序分析:首先创建一个链表,然后把指针翻转,利用3个指针不断的移动使指针翻转指向
2.程序源代码:
// example73.cpp : Defines the entry point for the console application.
////
#include "stdafx.h"
#include <stdlib.h> #include <stdio.h> struct list { int data; struct list *next; };
typedef struct list node; typedef node *link;
void displayList(link head){ link ptr;
ptr = head->next; printf("The list is: Head ->"); while(ptr != NULL) { printf(" %d ->", ptr->data); ptr=ptr->next; } printf("NULL\n"); }
link reverse(link head){ link ptr, qtr, temp; ptr = head->next; qtr = ptr->next; head = NULL;
while(ptr->next) { ptr->next = head; head = ptr; ptr = qtr; qtr = qtr->next; } ptr->next = head;
temp = (link)malloc(sizeof(node)); temp->next = ptr; return temp; }
int _tmain(int argc, _TCHAR* argv[]) { link ptr, head, tail; int num,i; tail=(link)malloc(sizeof(node)); tail->next = NULL; ptr=tail; printf("\nplease input the five node data==>\n"); for( i = 0; i <= 4; i++ ) { printf("The %dth node data: ",(5-i)); scanf("%d", &num); ptr->data = num; head = (link)malloc(sizeof(node)); head->next = ptr; ptr = head; } ptr = ptr->next;
printf("Before reverse\n"); displayList(head); link newHead = reverse(head); printf("After reverse\n"); displayList(newHead);
getchar(); getchar(); return 0; }
|
VS2005实现运行结果如下:
please input the five node data==>
The 5th node data: 5
The 4th node data: 4
The 3th node data: 3
The 2th node data: 2
The 1th node data: 1
Before reverse
The list is: Head -> 1 -> 2 -> 3 -> 4 -> 5 ->NULL
After reverse
The list is: Head -> 5 -> 4 -> 3 -> 2 -> 1 ->NULL
阅读(594) | 评论(0) | 转发(0) |