hackerrank Day15: Linked List

 1 #include <iostream>
 2 #include <cstddef>
 3 using namespace std;    
 4 class Node
 5 {
 6     public:
 7         int data;
 8         Node *next;
 9         Node(int d){
10             data=d;
11             next=NULL;
12         }
13 };
14 class Solution{
15     public:        
16          Node* insert(Node *head,int data)
17       {
18           Node *temp = new Node(data);
19           if(head == NULL){
20              head = temp;
21               return head;
22           }
23           Node *q, *p;
24           p = head;
25           q = head -> next;
26           
27           while(q){
28               p = q;
29               q = p -> next;
30           }
31           
32           p -> next = temp;
33           return head;
34       }
35           void display(Node *head)
36       {
37           Node *start=head;
38           while(start)
39           {
40               cout<<start->data<<" ";
41               start=start->next;
42           }
43       }
44 };
45 int main()
46 {
47     Node* head=NULL;
48       Solution mylist;
49     int T,data;
50     cin>>T;
51     while(T-->0){
52         cin>>data;
53         head=mylist.insert(head,data);
54     }    
55     mylist.display(head);
56         
57 }

 

posted @ 2016-05-31 10:25  琴影  阅读(395)  评论(0编辑  收藏  举报