Home > front end >  How to get the second last element of a list in C
How to get the second last element of a list in C

Time:05-09

i just started programing in C , and have a little bit of experience in C, but in this program was trying to use the C libraries that i am not familiar to at all.

The objective of the program is simple, i have a linked list and i need to get the second to last element of the list. What i did was reversing the list, using the reverse function, and then i was trying to get the new second element of the list, using std::next, because this would be the element i wanted. But i am unable to then print object, since it either print the pointer value or when i deference it says that std:cout is not able to print it because it does not know how to convert the value. Any help would be appreciated. Thanks in advance.

#include <list>

#define LOG(x) std::cout << x << std::endl;

typedef std::list<int> list;

list *getNextXValue(list *Head, int x)
{
    return std::next(Head, x);
}

/**
 * @brief Find last element of a linked list of ints
 *
 * @return int Program ended correctly
 */
int main()
{
    list listOne;
    list *aux = NULL;

    // Inserts all the elements in the list
    for (int i = 0; i < 100; i  )
    {
        listOne.insert(listOne.end(), i);
    }

    listOne.reverse();

    aux = getNextXValue(&listOne, 1);

    LOG(*aux);

    return 0;
}

CodePudding user response:

i was trying to get the new second element of the list, using std::next.

You are not getting the new second element of the list, what you are trying to get is the next new address of the list, since what you are passing is the pointer, the address of the list, not the iterator:

list *getNextXValue(list *Head, int x)
{
    return std::next(Head, x);
}

Try this instead:

#include <iostream>
#include <list>

#define LOG(x) std::cout << x << std::endl;

typedef std::list<int> list;

std::list<int>::iterator getNextXValue(std::list<int>::iterator Head, int x) {
  return std::next(Head, x);
}

/**
 * @brief Find last element of a linked list of ints
 *
 * @return int Program ended correctly
 */
int main() {
  list listOne;
  list *aux = NULL;

  // Inserts all the elements in the list
  for (int i = 0; i < 100; i  ) {
    listOne.insert(listOne.end(), i);
  }

  listOne.reverse();

  auto next = getNextXValue(listOne.begin(), 1);

  std::cout << *next << std::endl;

  return 0;
}

CodePudding user response:

I think you can do: std::list<int> l = {1, 2, 3}; // (types shouldn't matter), you can do *std::prev(l.end(), 2);

  •  Tags:  
  • c
  • Related