剑指Offer—15—反转链表

来源:互联网 发布:c语言if语句多个条件 编辑:程序博客网 时间:2024/06/05 18:57

反转链表 : 输入一个链表,反转链表后,输出链表的所有元素。

  • 思路:
    • 头插法
package A15反转链表;public class Solution {    public class ListNode {        int val;        ListNode next = null;        ListNode(int val) {            this.val = val;        }    }    public ListNode ReverseList(ListNode head) {        ListNode pre = null;        ListNode next = null;        while(head != null){            next = head.next;            head.next = pre;            pre = head;            head = next;        }        return pre;    }}
原创粉丝点击