单链表的创建及遍历
读入n值及n个整数,建立单链表并遍历输出。
输入格式:
读入n及n个整数。
输出格式:
输出n个整数,以空格分隔(最后一个数的后面没有空格)。
输入样例:
在这里给出一组输入。例如:
2
10 5
输出样例:
在这里给出相应的输出。例如:
10 5
注意:
整个题没难度,最基本的单链表建立。
注意申请内存空间的malloc函数的使用
struct NList* newNode = (struct NList*)malloc(sizeof( struct NList ));
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| #include <iostream> #include <malloc.h>
using namespace std;
struct NList { int num; struct NList* Next; };
int main(){ int n , x; cin >> n; struct NList* head , * r=head=NULL ; while(n--){ cin >> x; struct NList* newNode = (struct NList*)malloc(sizeof( struct NList )); newNode->num = x; if( head!=NULL ){ r->Next = newNode; r = newNode; } else { head = newNode; r = head; } } r = head; if( r!=NULL ){ cout << r->num; r = r->Next; } while( r!=NULL ){ cout << " " << r->num; r = r->Next; }
}
|