反转链表

反转链表

输入一个链表,反转链表后,输出新链表的表头。

代码实现

package 剑指offer;

/**
 * @author WangXiaoeZhe
 * @Date: Created in 2019/11/22 15:46
 * @description:
 */

public class Main7 {
    public static void main(String[] args) {

    }

    public class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode ReverseList(ListNode head){
        if (head == null) {
            return null;
        }
        ListNode pre=null;
        ListNode next=null;
        while (head != null) {
            /**
             * 标记第二个元素
             */

            next=head.next;
            head.next=pre;
            pre=head;
            head=next;
        }
        return pre;
    }
}
原文地址:https://www.cnblogs.com/wuhen8866/p/11912077.html