fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct Node{
  5. int val;
  6. Node* next;
  7. Node(int val):next(nullptr),val(val){};
  8. };
  9.  
  10. Node* removeLast(Node* head){
  11. if(head == nullptr)return nullptr;
  12. if(head->next == nullptr){
  13. delete head;
  14. return nullptr;
  15. }
  16.  
  17. Node* temp = head;
  18.  
  19. while(temp->next->next != nullptr){
  20. temp = temp->next;
  21. }
  22.  
  23. delete temp->next;
  24. temp->next = nullptr;
  25.  
  26. return head;
  27. }
  28.  
  29. Node* LL(vector<int>&a){
  30. Node* head = new Node(a[0]);
  31. Node* curr = head;
  32.  
  33. for(int i = 1;i<a.size();i++){
  34. curr->next = new Node(a[i]);
  35. curr = curr->next;
  36. }
  37. return head;
  38. }
  39. void print(Node* head){
  40. Node* temp = head;
  41.  
  42. while(temp!=nullptr){
  43. cout<<temp->val<<endl;
  44. temp = temp->next;
  45. }
  46. }
  47. int main() {
  48. int n;
  49. cin>>n;
  50.  
  51. vector<int>a(n);
  52. for(int i = 0 ;i < n ;i++){
  53. cin>>a[i];
  54. }
  55.  
  56. Node* head = LL(a);
  57. Node* temp = removeLast(head);
  58.  
  59. print(temp);
  60. return 0;
  61. }
Success #stdin #stdout 0s 5324KB
stdin
5
1 2 3 4 5
stdout
1
2
3
4