Reversing a linked list in java

Reversing a linked list in java

  • Find the middle of a given linked list
  • Write a function that counts the number of times a given int occurs in a Linked List
  • Check if a linked list is Circular Linked List
  • Count nodes in Circular linked list
  • Convert singly linked list into circular linked list
  • Exchange first and last nodes in Circular Linked List
  • Program to find size of Doubly Linked List
  • An interesting method to print reverse of a linked list
  • Can we reverse a linked list in less than O(n)?
  • Traversal of Circular Linked List
  • Delete a node in a Doubly Linked List
  • Reverse a Doubly Linked List
  • Detect loop or cycle in a linked list
  • Find length of loop/cycle in given Linked List
  • Remove duplicates from a sorted linked list
  • Intersection of two Sorted Linked Lists
  • QuickSort on Singly Linked List
  • Split a Circular Linked List into two halves
  • Deletion from a Circular Linked List
  • Merge Sort for Doubly Linked List
  • Find pairs with given sum in doubly linked list
  • Insert value in sorted way in a sorted doubly linked list
  • Remove duplicates from an unsorted doubly linked list
  • Rotate Doubly linked list by N nodes
  • Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it?
  • Modify contents of Linked List
  • Write a function to get the intersection point of two Linked Lists
  • Circular Linked List Implementation of Circular Queue
  • Josephus Circle implementation using STL list
  • The Great Tree-List Recursion Problem.
  • Clone a Linked List with next and Random Pointer
  • Convert given Binary Tree to Doubly Linked List in Linear time
  • Priority Queue using Doubly Linked List
  • Reverse a doubly linked list in groups of given size
  • Linked List representation of Disjoint Set Data Structures
  • Sublist Search (Search a linked list in another list)
  • Construct a linked list from 2D matrix
  • Partitioning a linked list around a given value and If we don’t care about making the elements of the list “stable”
  • Find the middle of a given linked list
  • Write a function that counts the number of times a given int occurs in a Linked List
  • Check if a linked list is Circular Linked List
  • Count nodes in Circular linked list
  • Convert singly linked list into circular linked list
  • Exchange first and last nodes in Circular Linked List
  • Program to find size of Doubly Linked List
  • An interesting method to print reverse of a linked list
  • Can we reverse a linked list in less than O(n)?
  • Traversal of Circular Linked List
  • Delete a node in a Doubly Linked List
  • Reverse a Doubly Linked List
  • Detect loop or cycle in a linked list
  • Find length of loop/cycle in given Linked List
  • Remove duplicates from a sorted linked list
  • Intersection of two Sorted Linked Lists
  • QuickSort on Singly Linked List
  • Split a Circular Linked List into two halves
  • Deletion from a Circular Linked List
  • Merge Sort for Doubly Linked List
  • Find pairs with given sum in doubly linked list
  • Insert value in sorted way in a sorted doubly linked list
  • Remove duplicates from an unsorted doubly linked list
  • Rotate Doubly linked list by N nodes
  • Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it?
  • Modify contents of Linked List
  • Write a function to get the intersection point of two Linked Lists
  • Circular Linked List Implementation of Circular Queue
  • Josephus Circle implementation using STL list
  • The Great Tree-List Recursion Problem.
  • Clone a Linked List with next and Random Pointer
  • Convert given Binary Tree to Doubly Linked List in Linear time
  • Priority Queue using Doubly Linked List
  • Reverse a doubly linked list in groups of given size
  • Linked List representation of Disjoint Set Data Structures
  • Sublist Search (Search a linked list in another list)
  • Construct a linked list from 2D matrix
  • Partitioning a linked list around a given value and If we don’t care about making the elements of the list “stable”
Читайте также:  Python two lists intersect

Источник

Reversing a Linked List in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Introduction

In this tutorial, we’ll implement two linked list reversal algorithms in Java.

2. Linked List Data Structure

A linked list is a linear data structure in which a pointer in each element determines the order. Each element of a linked list contains a data field to store the list data and a pointer field to point to the next element in the sequence. Also, we can use a head pointer to point to the start element of a linked list:

linked list

After we reverse the linked list, the head will point to the last element of the original linked list, and the pointer of each element will point to the previous element of the original linked list:

reversed linked list

In Java, we have a LinkedList class to provide a doubly-linked list implementation of the List and Deque interfaces. However, we’ll use a general singly-linked list data structure in this tutorial.

Let’s first start with a ListNode class to represent an element of a linked list:

public class ListNode < private int data; private ListNode next; ListNode(int data) < this.data = data; this.next = null; >// standard getters and setters >

The ListNode class has two fields:

  • An integer value to represent the data of the element
  • A pointer/reference to the next element

A linked list may contain multiple ListNode objects. For example, we can construct the above sample linked list with a loop:

ListNode constructLinkedList() < ListNode head = null; ListNode tail = null; for (int i = 1; i else < tail.setNext(node); >tail = node; > return head; >

3. Iterative Algorithm Implementation

Let’s implement the iterative algorithm in Java:

ListNode reverseList(ListNode head) < ListNode previous = null; ListNode current = head; while (current != null) < ListNode nextElement = current.getNext(); current.setNext(previous); previous = current; current = nextElement; >return previous; >

In this iterative algorithm, we use two ListNode variables, previous and current, to represent two adjacent elements in the linked list. For each iteration, we reverse these two elements and then shift to the next two elements.

In the end, the current pointer will be null, and the previous pointer will be the last element of the old linked list. Therefore, previous is also the new head pointer of the reversed linked list, and we return it from the method.

We can verify this iterative implementation with a simple unit test:

@Test void givenLinkedList_whenIterativeReverse_thenOutputCorrectResult() < ListNode head = constructLinkedList(); ListNode node = head; for (int i = 1; i LinkedListReversal reversal = new LinkedListReversal(); node = reversal.reverseList(head); for (int i = 5; i >= 1; i--) < assertNotNull(node); assertEquals(i, node.getData()); node = node.getNext(); >>

In this unit test, we first construct a sample linked list with five nodes. Also, we verify that each node in the linked list contains the correct data value. Then, we call the iterative function to reverse the linked list. Finally, we check the reversed linked list to make sure the data are reversed as expected.

4. Recursive Algorithm Implementation

Now, let’s implement the recursive algorithm in Java:

ListNode reverseListRecursive(ListNode head) < if (head == null) < return null; >if (head.getNext() == null) < return head; >ListNode node = reverseListRecursive(head.getNext()); head.getNext().setNext(head); head.setNext(null); return node; >

In the reverseListRecursive function, we recursively visit each element in the linked list until we reach the last one. This last element will become the new head of the reversed linked list. Also, we append the visited element to the end of the partially reversed linked list.

Similarly, we can verify this recursive implementation with a simple unit test:

@Test void givenLinkedList_whenRecursiveReverse_thenOutputCorrectResult() < ListNode head = constructLinkedList(); ListNode node = head; for (int i = 1; i LinkedListReversal reversal = new LinkedListReversal(); node = reversal.reverseListRecursive(head); for (int i = 5; i >= 1; i--) < assertNotNull(node); assertEquals(i, node.getData()); node = node.getNext(); >>

5. Conclusion

In this tutorial, we implemented two algorithms to reverse a linked list. As always, the source code for the article is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Reverse a LinkedList in Java

Assuming you have gone through LinkedList in java and know about linked list. This post contains different examples for reversing a linked list which are given below: 1. By writing our own function(Using additional space): reverseLinkedList() method contains logic for reversing string objects in a linked list. This method takes a linked list as a parameter, traverses all the elements in reverse order and adds it to the newly created linked list. Algorithm: Step 1. Create a linked list with n elements Step 2. Create an empty linked list which will be used to store reversed elements Step 3. Start traversing the list from ‘n’ to ‘0’ and store the elements in the newly created list. Step 4. The elements will be stored in the following order: n, n-1, n-2, ……0 Step 5. Return the list to the caller and print it

Example: Step 1: LL: 1 -> 2 -> 3 -> 4 -> 5 where 'LL' is the linked list with n elements Step 2: 'Rev' is an empty linked list Step 3: Start traversing, the below passes are the intermediate steps while traversing 1st pass: Rev: 5 2nd pass: Rev: 5 -> 4 3rd pass: Rev: 5 -> 4 -> 3 4th pass: Rev: 5 -> 4 -> 3 -> 2 5th pass: Rev: 5 -> 4 -> 3 -> 2 -> 1 Step 4: nth element of 'LL' is stored in 0th position of 'Rev', n-1 element of LL is stored in 1st position of Rev and so on. Step 5: Return Rev: 5 -> 4 -> 3 -> 2 -> 1 to the calling function.

Источник

Оцените статью