#1 1.3反转链表

80 阅读1分钟

反转链表

[leetcode原题链接](https://leetcode.cn/leetbook/read/illustration-of-algorithm/7fadz7/)

代码记录

/**
 * Definition for singly-linked list.
 * 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; }
 * }
 */
class Solution {
    public ListNode trainningPlan(ListNode head) {
        //递归
        if(head==null||head.next==null){
            return head;
        }
        ListNode temp=trainningPlan(head.next);//必须返回末尾节点
        head.next.next=head;
        head.next=null;
        return temp;
    }
}
/**
 * Definition for singly-linked list.
 * 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; }
 * }
 */
class Solution {
    public ListNode trainningPlan(ListNode head) {

        //使用三指针反转链表
        if(head==null||head.next==null) return head;
        ListNode pre=null;
        ListNode p=head;
        ListNode pNext=p.next;
        while(pNext!=null){
            p.next=pre;
            pre=p;
            p=pNext;
            pNext=pNext.next;
        }
        p.next=pre;//末尾节点
        return p;
    }
}
/**
 * Definition for singly-linked list.
 * 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; }
 * }
 */
class Solution {
    public ListNode trainningPlan(ListNode head) {

        //使用hashmap进行反转
        if(head==null||head.next==null){
            return head;
        }
        int count=0;
        ListNode p=head;
        HashMap<Integer,ListNode> map=new HashMap<Integer,ListNode>();
        while(p!=null){
            map.put(count++,p);
            p=p.next;
        }

        for(int i=count-1;i>0;i--){
            map.get(i).next=map.get(i-1);
        }
        map.get(0).next=null;//处理头节点
        return map.get(count-1);
    }
}
/**
 * Definition for singly-linked list.
 * 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; }
 * }
 */
class Solution {
    public ListNode trainningPlan(ListNode head) {

        //使用栈
        if(head==null||head.next==null){
            return head;
        }
        Stack<ListNode> stack=new Stack<ListNode>();
        ListNode p=head;
        while(p!=null){
            stack.push(p);
            p=p.next;
        }
        ListNode result=stack.peek();
        while(!stack.isEmpty()){
            stack.pop().next=stack.isEmpty()?null:stack.peek();
        }
        return result;
    }
}