随笔-反转链表

版权声明:中华人民共和国持有版权 https://blog.csdn.net/Fly_Fly_Zhang/article/details/85341908

题目:

反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

思路:pre作为反转后的头结点,curNext作为老节点的头节点

常规版本

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre=null;
        ListNode cur=head;
        ListNode curNext;
        while(cur!=null){
            curNext=cur.next;
            cur.next=pre;
            pre=cur;
            cur=curNext;
        }
        return pre;
    }
}

递归版本:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverse(ListNode cur,ListNode pre){
        if(cur==null){
            return pre;
        }else{
            ListNode curNext=cur.next;
            cur.next=pre;   接新链表
            pre=cur;  新的头部
            cur=curNext;  下一次反转
            return reverse(cur,pre);
        }
    }
    public ListNode reverseList(ListNode head) {
        ListNode pre=null;
        ListNode cur=head; 
        return reverse(cur,pre);
    }
}

猜你喜欢

转载自blog.csdn.net/Fly_Fly_Zhang/article/details/85341908