Leedcode2 逆置单链表

public class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

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

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

方法一:迭代法

1. 从前向后反转,使cur指向当前结点,pre指向父结点,令cur.next = pre

2. 反转之后cur.next修改为pre,需要临时保存cur.next

3.迭代结束后,cur指向null,pre指向最后一个结点,返回pre

4. 头结点经过反转后变成尾结点,下一结点指向null,所以pre初始化为null 

public class Solution_1 {
    public ListNode reverseList(ListNode head){
        ListNode cur = head,pre = null;
        while(cur != null){
            ListNode t = cur.next;//前进一位
            cur.next = pre;//后一个结点指向前一个结点
            pre = cur;//pre指向下一个结点
            cur = t;
        }
        return pre;
    }
}
方法二:递归
public class Solution_2 {
    public ListNode reverseList(ListNode head){
        if(head == null || head.next == null){
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}

方法三:使用虚拟头结点从头插入反转链表

public class Solution_3 {
    public ListNode reverseList(ListNode head){
        ListNode dummy = new ListNode(0,null);//dummy哑结点
        ListNode cur = head;
        ListNode tmp;
        while(cur != null){
            tmp = cur.next;//临时保存cur.next
            cur.next = dummy.next;
            dummy.next = cur;
            cur = tmp;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/crazy_tan/article/details/130662052