tell me how to reverse a linked list in java
- User
tell me how to reverse a linked list in java
- Assistant
Sure! Here's an example of how to reverse a singly linked list in Java:
javapublic class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public class ReverseLinkedList { public ListNode reverseList(ListNode head) { ListNode prev = null; ListNode curr = head; while (curr != null) { ListNode nextNode = curr.next; curr.next = prev; prev = curr; curr = nextNode; } return prev; } }In this code, ListNode represents the nodes of the linked list, and each ListNode object has an integer value and a next pointer that points to the next node in the list.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.