leetCode_206 Reverse a linked list

topic:

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Advanced:
You can reverse the linked list iteratively or recursively. Can you solve this problem in two ways?

Code first

    public static ListNode reverseList(ListNode head) {
        //申请节点,pre和 cur,pre指向null,cur指向当前节点
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {//当前节点不为null就一直循环
            //记录当前节点的下一个节点
            ListNode tmp = cur.next;
            //然后将当前节点指向pre,指向反转
            cur.next = pre;
            //pre和cur节点都前进一位
            pre = cur;//pre右移到cur位置
            cur = tmp;//cur右移到tmp位置,继续循环,tmp指向cur的下一个节点
        }
        return pre;
    }

Next, write a test class to test

package leetCode_206;

public class ReverseList {

    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
        }

        public static String print(ListNode listNode){//打印节点的方法
            StringBuilder sb = new StringBuilder();
            while (listNode!=null){
                sb.append(listNode.val);
                listNode = listNode.next;
            }
            return sb.toString();
        }
    }

    public static ListNode reverseList(ListNode head) {
        //申请节点,pre和 cur,pre指向null,cur指向当前节点
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {//当前节点不为null就一直循环
            //记录当前节点的下一个节点
            ListNode tmp = cur.next;
            //然后将当前节点指向pre,指向反转
            cur.next = pre;
            //pre和cur节点都前进一位
            pre = cur;//pre右移到cur位置
            cur = tmp;//cur右移到tmp位置,继续循环,tmp指向cur的下一个节点
        }
        return pre;
    }

    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);//新建节点1
        listNode.next = new ListNode(2);//1指向下一个节点2
        listNode.next.next = new ListNode(3);//2指向下一个节点3
        listNode.next.next.next = new ListNode(4);//3指向下一个节点4
        System.out.println(listNode.print(listNode));//1234
        listNode = reverseList(listNode);//单链表反转
        System.out.println(listNode.print(listNode));//4321
    }

}

Problem-solving tutorial welcome to visit B station https://www.bilibili.com/video/BV1pJ411s7P4?p=2

This is the end.

Guess you like

Origin blog.csdn.net/weixin_43419256/article/details/107785523