數據結構實驗之鏈表二:逆序建立鏈表 (sdut oj)


數據結構實驗之鏈表二:逆序建立鏈表

Time Limit: 1000MS Memory Limit: 65536KB


Problem Description

輸入整數個數N,再輸入N個整數,按照這些整數輸入的相反順序建立單鏈表,並依次遍歷輸出單鏈表的數據。


Input

第一行輸入整數N;;
第二行依次輸入N個整數,逆序建立單鏈表。


Output

依次輸出單鏈表所存放的數據。


Example Input

10
11 3 5 27 9 12 43 16 84 22 


Example Output

22 84 16 43 12 9 27 5 3 11 

Hint

不能使用數組!

Author








參考代碼


#include<stdio.h>
#include<stdlib.h>

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

int main()
{
  int n;
  struct node *head,*p;
  head = (struct node *)malloc(sizeof(struct node));
  head->next = NULL;
  scanf("%d",&n);
  while(n--)
  {
     p = (struct node *)malloc(sizeof(struct node));
     scanf("%d",&p->data);
     p->next = head->next;
     head->next = p;
  }
  p = head->next;
  printf("%d",p->data);
  p = p->next;
  while(p)
  {
    printf(" %d",p->data);
    p = p->next;
  }
  printf("\n");
  return 0;
}



發佈了189 篇原創文章 · 獲贊 60 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章