反转链表

来源:互联网 发布:java商品信息管理系统 编辑:程序博客网 时间:2024/06/07 05:35

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


通过递归的方式修改指针

/*public class ListNode {    int val;    ListNode next = null;     ListNode(int val) {        this.val = val;    }}*/public class Solution {    public ListNode ReverseList(ListNode head) {        if(head == null)            return null ;        ListNode temp = head ;        ListNode ans = change(head) ;        temp.next = null ;        return ans ;    }    public ListNode change(ListNode head){        if(head.next == null)            return head ;        ListNode next = head.next ;        ListNode node = change(next) ;        next.next = head ;        return node;    }}

直接遍历修改指针

/*public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}*/public class Solution {    public ListNode ReverseList(ListNode head) {        ListNode pre = null ;         while(head != null){            ListNode next = head.next ;             head.next = pre ;             pre = head ;             head = next ;         }        return pre ; }}
0 0