Single-chain table reverse Java, single-chain reverse java

Source: Internet
Author: User

Single-chain table reverse Java, single-chain reverse java
Common linked list operations-reverse

Let's first define a node class for a single-chain table.

1 public class ListNode {2 int val; 3 ListNode next = null; // point to the next node 4 5 ListNode (int val) {6 this. val = val; 7} 8}

 

Two methods are available for single-chain table reversal.

1. Use recursion to reverse from the back to the back. Start from the Start Node, locate it until the end node is found, and then start to reverse.

1 public ListNode reverseList (ListNode head) {2 if (head = null | head. next = null) 3 return head; 4 5 ListNode prev = reverseList (head. next); // recursive call, first reverse the next node 6 7 head. next. next = head; // point the pointer field of the current node to the 8 head of the previous node. next = null; // the pointer field of the previous node makes it null; 9 return prev; // The first node 10 of the new linked list after the reversal}

 

2. Use traversal to reverse the query. First, save the next node, and then point the current node to the previous node. Then, move the node downward and continue the cycle for the next reversal.

1 public ListNode reverseList (ListNode head) {2 if (head = null) {3 return null; 4} 5 ListNode pre = null; 6 ListNode next = null; 7 while (head! = Null) {8 // save the next node to prevent 9 next = head loss. next; 10 // point his next node to the 11 head of the previous node. next = pre; 12 13 // after the head points to the pre, it will continue to reverse the next node in turn 14 // Let the pre and head move one node backward, continue the next reversal of 15 pre = head; 16 head = next; 17} 18 return pre; 19}

 

After finishing online programming, you can easily record it and view it later.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.