How to find nth element from the end of a singly linked list?

后端 未结 28 1098
感动是毒
感动是毒 2020-12-04 06:08

The following function is trying to find the nth to last element of a singly linked list.

For example:

If the elements are

28条回答
  •  春和景丽
    2020-12-04 06:28

    can you use extra data structure .. if so it will be simple ... start pushing all the nodes to a stack, maintain a counter a pop it. as per your example, 8->10->5->7->2->1->5->4->10->10 start reading the linked list and start pushing the nodes or the node->data onto a stack. so the stack will look like top->{10, 10,4, 5, 1, 2, 7, 5, 10, 8}<-bottom.

    now start popping from the top of the stack maintaining a counter=1 and every time you pop increase the counter by 1, when you reach n-th element (in your example 7th element) stop popping.

    note: this will print or retrieve the data/nodes in reverse order

提交回复
热议问题