牛客网反转链表题目链接如下:反转链表

反转链表有两种解法,一种是新建逆序链表,但是很明显要开辟新内存构建新链表,算法空间复杂度比较大;另外一种解法是移动指针。具体代码如下:

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

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
//游动指针
        ListNode p = head;
        while (p != null && p.next!=null) {
            ListNode q = p.next;
            p.next = q.next;
            q.next = head;
            head = q;
        }
        return head;
    }
}

完整测试代码如下:

public class Solution {
    public static ListNode ReverseList(ListNode head) {
        //游动指针
        ListNode p = head;
        while (p != null && p.next!=null) {
            ListNode q = p.next;
            p.next = q.next;
            q.next = head;
            head = q;
        }
        return head;
    }

    public static void main(String[] args) {
        ListNode head=add(10);
        head=ReverseList(head);
        print(head);
    }

    private static void print(ListNode head) {
        ListNode p = head;
        while(p!=null){
            System.out.print(p.val+" ");
            p = p.next;
        }
    }

    private static ListNode add(int num) {
        ListNode head = new ListNode(1);
        ListNode p = head;
        for(int i=2;i<=num;i++){
            ListNode temp = new ListNode(i);
            p.next = temp;
            p = temp;
        }
        return head;
    }
}

class ListNode {
    int val;
    ListNode next = null;

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

    @Override
    public String toString() {
        return "ListNode{" +
                "val=" + val +
                ", next=" + next +
                '}';
    }
}

以1/2/3逆序为3/2/1为例:

-----0
-----1
-----2-1
-----3-1
-----4-1
-----5-1
-----6-1
-----7-1