[Groovy] How do I handle and manipulate data structures like linked lists or stacks in Groovy?

In Groovy, you can handle and manipulate data structures like linked lists and stacks using the built-in collections and data structures available in the language. Here are some examples:

  1. Linked Lists: Groovy doesn't provide a built-in linked list implementation, but you can use the java.util.LinkedList class from Java. Here's how you can create and manipulate a linked list:
 1import java.util.LinkedList
 2
 3def linkedList = new LinkedList<Integer>() // Create a new linked list
 4
 5linkedList.add(1) // Add elements to the linked list
 6linkedList.add(2)
 7linkedList.add(3)
 8
 9println(linkedList) // Output: [1, 2, 3]
10
11linkedList.removeFirst() // Remove the first element
12println(linkedList) // Output: [2, 3]
13
14println(linkedList.getFirst()) // Output: 2
  1. Stacks: In Groovy, you can use the java.util.Stack class from Java to handle stacks. Here's an example:
 1import java.util.Stack
 2
 3def stack = new Stack<Integer>() // Create a new stack
 4
 5stack.push(1) // Push elements to the stack
 6stack.push(2)
 7stack.push(3)
 8
 9println(stack) // Output: [1, 2, 3]
10
11println(stack.pop()) // Pop and remove the top element from the stack
12println(stack) // Output: [1, 2]

Alternatively, you can simulate a stack using a list in Groovy:

 1def stack = [] // Create an empty list
 2
 3stack.push(1) // Push elements to the stack
 4stack.push(2)
 5stack.push(3)
 6
 7println(stack) // Output: [1, 2, 3]
 8
 9println(stack.pop()) // Pop and remove the top element from the stack
10println(stack) // Output: [1, 2]

These are just basic examples, and you can perform various operations like traversing, inserting, or deleting elements based on your requirements.