刷题-反转链表

方法一:

1.根据头插法反转链表

public class Solution {
    public ListNode ReverseList(ListNode head) {
        ListNode newHead = null;
        ListNode node = null;
        while(head != null){
            //做头删法
            node = head;
            head = head.next;
            
            //头插法
            node.next = newHead;
            newHead = node;
        }
        return newHead;
    }
}

 

2.定义两个指针直接反转

public class Solution {
    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;
    }
    
}

 

posted @ 2020-10-26 21:57  死磕之路  阅读(97)  评论(0)    收藏  举报