Java single-chain reversal

Source: Internet
Author: User

This article describes two methods of unidirectional list inversion. Records, such as the following:

1.

Package Com.leetcode;public class Listreverse {public static void main (string[] args) {node Node1 = new Node (1); Node Node2 = new node (2); Node Node3 = new node (3); Node Node4 = new node (4); node1.next = Node2;node2.next = Node3;node3.next = Node4; Node head = reverse (Node1); while (head! = null) {System.out.println (head.val); head = Head.next;}} public static node reverse (node Head) {Node cur = head, post = Head.next;head.next = Null;while (post! = NULL) {node TMP = PO St;post = Post.next;tmp.next = Cur;cur = tmp;} return cur;} Static class Node{int Val; Node Next; Node (int val) {this.val = Val;this.next = null;}}}

The result of the execution is:

4321

2.

Package Com.leetcode;public class Listreverse {public static void main (string[] args) {node Node1 = new Node (1); Node Node2 = new node (2); Node Node3 = new node (3); Node Node4 = new node (4); node1.next = Node2;node2.next = Node3;node3.next = Node4; Node head = reverse (Node1); while (head! = null) {System.out.println (head.val); head = Head.next;}} public static node reverse (node Head) {Node dummy = new Node ( -1);d ummy.next = head; Node pre = dummy, cur = head, post = Head.next;while (post! = null) {Cur.next = Post.next;post.next = Pre.next;pre.next = PO St;post = Cur.next;} return dummy.next;} Static class Node{int Val; Node Next; Node (int val) {this.val = Val;this.next = null;}}}

The result of the execution is:

4321



Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

Java single-chain reversal

Related Article

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.