我所使用的方法在输入的时候是使用一个栈存储所有的数据,利用的是其先进后出的数据结构。
当然,用一个数组也是可以的= =,而且我觉得还可以保存数据,而用stack的话操作比较麻烦。
#include#include #include #include #define LEN sizeof(Node)using namespace std;struct Node{ int data; Node *next;};stack s;int tot = 0;Node *Node_Creat(){ Node *head; head = (Node *)malloc(LEN); if(head == NULL) { printf("Overflow\n"); exit(1); } head = NULL; Node *p1,*p2; p1 = p2 = (Node *)malloc(LEN); if(p1 == NULL || p2 == NULL) { printf("Overflow\n"); exit(1); } scanf("%d",&p1 -> data); while(p1 -> data >= 0) { tot++; s.push(p1 -> data); if(head == NULL) { head = p1; } else { p2 -> next = p1; } p2 = p1; p1 = (Node *)malloc(LEN); if(p1 == NULL) { printf("Overflow\n"); exit(1); } scanf("%d",&p1 -> data); } p2 -> next = NULL; return head;}void Node_Print(Node *head){ if(head == NULL) { printf("EMPTY!\n"); return ; } Node *p = head; while(p != NULL) { printf("%d ",p -> data); p = p -> next; } printf("\n");}void Node_ReverseFound(int num){ int i; int data = 0; if(num > tot) { printf("NOT FOUND\n"); } for(i = 1; i < num; i++) { s.pop(); } printf("%d\n",s.top());}int main(){ Node *head; head = Node_Creat(); Node_Print(head); int num; scanf("%d",&num); printf("Reverse Found num: %d\n",num); Node_ReverseFound(num); return 0;}