{"id":83445,"date":"2020-09-27T14:56:36","date_gmt":"2020-09-27T14:56:36","guid":{"rendered":"https:\/\/www.baeldung.com\/?p=87757"},"modified":"2020-09-27T14:56:36","modified_gmt":"2020-09-27T14:56:36","slug":"reversing-a-linked-list-in-java","status":"publish","type":"post","link":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/2020\/09\/27\/reversing-a-linked-list-in-java\/","title":{"rendered":"Reversing a Linked List in Java"},"content":{"rendered":"<p class=\"syndicated-attribution\"><meta name= \\\"keywords \\\" content= \\\"\u96fb\u5b50\u8a08\u7b97\u6a5f, \u6559\u80b2, IT \u96fb\u8166\u73ed,\u96fb\u8166\u88dc\u7fd2\uff0c \u96fb\u8166\u73ed\uff0c \u5bb6\u6559\uff0c \u79c1\u4eba\u8001\u5e2b\uff0c \u8cc7\u8a0a\u6280\u8853\uff0c \u7a0b\u5e8f\u8a2d\u8a08\uff0c \u96fb\u5b50\u8a08\u7b97\u6a5f\uff0c \u904a\u6232\uff0c \u860b\u679c\uff0c \u96fb\u5f71\uff0c \u8a08\u7b97\u6a5f\uff0c\u7de8\u78bc\uff0c Java\uff0c C\/C++\uff0c JavaScript\uff0c PHP\uff0c HTML\uff0c CSS\uff0c MySQL\uff0c mobile\uff0c Android\uff0c \u52d5\u6f2b\uff0c Python\uff0c teacher\uff0c \u88dc\u7fd2\uff0c \u96fb\u8166\u88dc\u7fd2 \u8cc7\u8a0a, \u7535\u5b50\u8ba1\u7b97\u673a, IT ,Game, apple, movie, Computer,student,Java,\u6559\u80b2, ,\u5b66\u751f, \u5b66\u4e60, learn, \u6559\u5b66,  Android, apple,anime, animation, \u4fe1\u606f\u6280\u672f, \u7a0b\u5e8f\u8bbe\u8ba1, \u79fb\u52a8\u7535\u8bdd, \u8cc7\u8a0a\u79d1\u6280,Game, Jeu, Juego,Call Of Duty ,\u4f7f\u547d\u53ec\u559a , \u6e38\u620f, \u7535\u5b50\u6e38\u620f,, \u591a\u4eba\u7535\u5b50\u6e38\u620f, \u7f51\u7edc\u6e38\u620f\uff0conline\uff0conline game, \u624b\u673a\u6e38\u620f, mobile \\\"><\/p>\n<h2  data-id=\"introduction\"><strong>1. Introduction<\/strong><\/h2>\n<div class=\"bd-anchor\" id=\"introduction\"><\/div>\n<p>In this tutorial, we&#8217;ll implement <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/cs\/reverse-linked-list\">two linked list reversal algorithms<\/a> in Java.<\/p>\n<h2  data-id=\"definition\"><strong>2. <b>Linked List Data Structure<\/b><\/strong><\/h2>\n<div class=\"bd-anchor\" id=\"definition\"><\/div>\n<p>A linked list is a linear data structure in which a pointer in each element determines the order.\u00a0<strong>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.<\/strong> Also, we can use a <em>head<\/em> pointer to point to the start element of a linked list:<\/p>\n<p><a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~www.baeldung.com\/wp-content\/uploads\/2020\/09\/linkedlist.png\"><img decoding=\"async\" class=\"alignnone size-full wp-image-228293\" src=\"http:\/\/www.baeldung.com\/wp-content\/uploads\/2020\/09\/linkedlist.png\" alt=\"\" \/><\/a><\/p>\n<p>After we reverse the linked list, the <em>head<\/em> 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:<\/p>\n<p><a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/wp-content\/uploads\/2020\/09\/reversedlinkedlist1.png\"><img decoding=\"async\" class=\"alignnone size-full wp-image-234769\" src=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2020\/09\/reversedlinkedlist1.png\" alt=\"\" \/><\/a><\/p>\n<p>In Java, we have a <em><a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-linkedlist\">LinkedList<\/a> <\/em>class to provide a\u00a0doubly-linked list implementation of the\u00a0<em>List<\/em>\u00a0and\u00a0<em>Deque<\/em> interfaces. However, we&#8217;ll use a general singly-linked list data structure in this tutorial.<\/p>\n<p>Let&#8217;s first start with a <em>ListNode<\/em> class to represent an element of a linked list:<\/p>\n<pre><code class=\"language-java\">public class ListNode {\r\n    private int data;\r\n    private ListNode next;\r\n    ListNode(int data) {\r\n        this.data = data;\r\n        this.next = null;\r\n    }\r\n   \/\/ standard getters and setters\r\n}<\/code><\/pre>\n<p>The <em>ListNode\u00a0<\/em>class has two fields:<\/p>\n<ul data-id=\"96bc11bd46ff493261c33b38ab1f7674\">\n<li>An integer value to represent the data of the element<\/li>\n<li>A pointer\/reference to the next element<\/li>\n<\/ul>\n<p>A linked list may contain multiple <em>ListNode<\/em> objects. For example, we can construct the above sample linked list with a loop:<\/p>\n<pre><code class=\"language-java\">ListNode constructLinkedList() {\r\n    ListNode head = null;\r\n    ListNode tail = null;\r\n    for (int i = 1; i &lt;= 5; i++) {\r\n        ListNode node = new ListNode(i);\r\n        if (head == null) {\r\n            head = node;\r\n        } else {\r\n            tail.setNext(node);\r\n        }\r\n        tail = node;\r\n    }\r\n    return head;\r\n}<\/code><\/pre>\n<h2  data-id=\"iterative\"><strong>3. <b>Iterative Algorithm Implementation<\/b><\/strong><\/h2>\n<div class=\"bd-anchor\" id=\"iterative\"><\/div>\n<p>Let&#8217;s implement the <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/cs\/reverse-linked-list#iterative\">iterative algorithm<\/a> in Java:<\/p>\n<pre><code class=\"language-java\">ListNode reverseList(ListNode head) {\r\n    ListNode previous = null;\r\n    ListNode current = head;\r\n    while (current != null) {\r\n        ListNode nextElement = current.getNext();\r\n        current.setNext(previous);\r\n        previous = current;\r\n        current = nextElement;\r\n    }\r\n    return previous;\r\n}<\/code><\/pre>\n<p>In this iterative algorithm, we use two <em>ListNode<\/em> variables, <em>previous<\/em> and <em>current<\/em>, 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.<\/p>\n<p>In the end, the <em>current <\/em>pointer will be <em>null,<\/em> and the <em>previous<\/em> pointer will be the last element of the old linked list. Therefore, <em>previous\u00a0<\/em>is also the new head pointer of the reversed linked list, and we return it from the method.<\/p>\n<p>We can verify this iterative implementation with a simple unit test:<\/p>\n<pre><code class=\"language-java\">@Test\r\npublic void givenLinkedList_whenIterativeReverse_thenOutputCorrectResult() {\r\n    ListNode head = constructLinkedList();\r\n    ListNode node = head;\r\n    for (int i = 1; i &lt;= 5; i++) {\r\n        assertNotNull(node);\r\n        assertEquals(i, node.getData());\r\n        node = node.getNext();\r\n    }\r\n \r\n    LinkedListReversal reversal = new LinkedListReversal();\r\n    node = reversal.reverseList(head);\r\n \r\n    for (int i = 5; i &gt;= 1; i--) {\r\n        assertNotNull(node);\r\n        assertEquals(i, node.getData());\r\n        node = node.getNext();\r\n    }\r\n}<\/code><\/pre>\n<p>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.<\/p>\n<h2  data-id=\"recursive\"><strong>4. Recursive<b>\u00a0Algorithm Implementation<\/b><\/strong><\/h2>\n<div class=\"bd-anchor\" id=\"recursive\"><\/div>\n<p>Now, let&#8217;s implement the <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/cs\/reverse-linked-list#recursive\">recursive algorithm<\/a> in Java:<\/p>\n<pre><code class=\"language-java\">ListNode reverseListRecursive(ListNode head) {\r\n    if (head == null) {\r\n        return null;\r\n    }\r\n    if (head.getNext() == null) {\r\n        return head;\r\n    }\r\n    ListNode node = reverseListRecursive(head.getNext());\r\n    head.getNext().setNext(head);\r\n    head.setNext(null);\r\n    return node;\r\n}<\/code><\/pre>\n<p>In the <em>reverseListRecursive <\/em>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.<\/p>\n<p>Similarly, we can verify this recursive implementation with a simple unit test:<\/p>\n<pre><code class=\"language-java\">@Test\r\npublic void givenLinkedList_whenRecursiveReverse_thenOutputCorrectResult() {\r\n    ListNode head = constructLinkedList();\r\n    ListNode node = head;\r\n    for (int i = 1; i &lt;= 5; i++) {\r\n        assertNotNull(node);\r\n        assertEquals(i, node.getData());\r\n        node = node.getNext();\r\n    }\r\n \r\n    LinkedListReversal reversal = new LinkedListReversal();\r\n    node = reversal.reverseListRecursive(head);\r\n \r\n    for (int i = 5; i &gt;= 1; i--) {\r\n        assertNotNull(node);\r\n        assertEquals(i, node.getData());\r\n        node = node.getNext();\r\n    }\r\n}<\/code><\/pre>\n<h2  data-id=\"conclusion\"><strong>5. Conclusion<\/strong><\/h2>\n<div class=\"bd-anchor\" id=\"conclusion\"><\/div>\n<p>In this tutorial, we implemented two algorithms to reverse a linked list. As always, the source code for the article is available\u00a0<a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/github.com\/eugenp\/tutorials\/tree\/master\/algorithms-miscellaneous-6\">over on GitHub<\/a>.<\/p>\n<p>The post <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-reverse-linked-list\/\" >Reversing a Linked List in Java<\/a> first appeared on <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/\" >Baeldung<\/a>.<\/p>\n<p><Img align=\"left\" border=\"0\" height=\"1\" width=\"1\" alt=\"\" style=\"border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;\" hspace=\"0\" src=\"https:\/\/feeds.feedblitz.com\/~\/i\/636031154\/0\/baeldung\"><\/p>\n<div style=\"clear:both;padding-top:0.2em;\"><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/636031154\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Share on Google+\" href=\"https:\/\/feeds.feedblitz.com\/_\/30\/636031154\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/googleplus20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/636031154\/baeldung,http%3A%2F%2Fwww.baeldung.com%2Fwp-content%2Fuploads%2F2020%2F09%2Flinkedlist.png\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Tweet This\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/636031154\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/twitter20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/636031154\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/636031154\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-reverse-linked-list#respond\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>&#160;<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-reverse-linked-list\/feed\/\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>&#160;<\/div>\n\n<p class=\"syndicated-attribution\"><figure class= \\\"wp-block-image alignnone \\\"><img src= \\\"http:\/\/itteacheritfreelance.hk\/test\/wordpress\/wp-content\/uploads\/2016\/05\/logo2-2.png\\\" alt=\\\"IT\u96fb\u8166\u88dc\u7fd2 java\u88dc\u7fd2 \u70ba\u5927\u5bb6\u914d\u5c0d\u96fb\u8166\u88dc\u7fd2,IT freelance, \u79c1\u4eba\u8001\u5e2b, PHP\u88dc\u7fd2,CSS\u88dc\u7fd2,XML,Java\u88dc\u7fd2,MySQL\u88dc\u7fd2,graphic design\u88dc\u7fd2,\u4e2d\u5c0f\u5b78ICT\u88dc\u7fd2,\u4e00\u5c0d\u4e00\u79c1\u4eba\u88dc\u7fd2\u548cFreelance\u81ea\u7531\u5de5\u4f5c\u914d\u5c0d\u3002\\\"\/><figcaption>\u7acb\u523b\u8a3b\u518a\u53ca\u5831\u540d\u96fb\u8166\u88dc\u7fd2\u8ab2\u7a0b\u5427!<\/figcaption><\/figure>\r\n<\/br>Find A Teacher Form:\r\n<\/br>https:\/\/docs.google.com\/forms\/d\/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ\/viewform?edit_requested=true#responses\r\n<\/br><\/br>Email:\r\n<\/br>public1989two@gmail.com<br><br><br><br><br><br><br>\r\n<a href=www.itsec.hk style=color:#FFFFFF;>www.itsec.hk<\/a><br>\r\n<a href=\\\"www.itsec.vip\\\" style=color:#FFFFFF;>www.itsec.vip<\/a><br>\r\n<a href=\\\"www.itseceu.uk\\\" style=color:#FFFFFF;>www.itseceu.uk<\/a><br><\/p>","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p>Implement two linked list reversal algorithms in Java<\/p>\n<p>The post <a rel=\"NOFOLLOW noopener noreferrer\" href=\"https:\/\/feeds.feedblitz.com\/~\/636031154\/0\/baeldung~Reversing-a-Linked-List-in-Java\/\" target=\"_blank\">Reversing a Linked List in Java<\/a> first appeared on <a rel=\"NOFOLLOW noopener noreferrer\" href=\"https:\/\/www.baeldung.com\/\" target=\"_blank\">Baeldung<\/a>.<\/p>\n<div><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/636031154\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\"><\/a>&nbsp;<a title=\"Share on Google+\" href=\"https:\/\/feeds.feedblitz.com\/_\/30\/636031154\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/googleplus20.png\"><\/a>&nbsp;<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/636031154\/baeldung,http%3A%2F%2Fwww.baeldung.com%2Fwp-content%2Fuploads%2F2020%2F09%2Flinkedlist.png\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\"><\/a>&nbsp;<a title=\"Tweet This\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/636031154\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/twitter20.png\"><\/a>&nbsp;<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/636031154\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\"><\/a>&nbsp;<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/636031154\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\"><\/a>&nbsp;<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-reverse-linked-list#respond\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>&nbsp;<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-reverse-linked-list\/feed\/\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>&nbsp;<\/div>\n<\/div>","protected":false},"author":914,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"slim_seo":{"title":"Reversing a Linked List in Java - ITTeacherITFreelance.hk","description":"Implement two linked list reversal algorithms in Java The post Reversing a Linked List in Java first appeared on Baeldung . &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &"},"footnotes":""},"categories":[6],"tags":[],"_links":{"self":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/83445"}],"collection":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/users\/914"}],"replies":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/comments?post=83445"}],"version-history":[{"count":5,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/83445\/revisions"}],"predecessor-version":[{"id":85413,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/83445\/revisions\/85413"}],"wp:attachment":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/media?parent=83445"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/categories?post=83445"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/tags?post=83445"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}