LeedCode_206:反转链表

https://leetcode-cn.com/problems/reverse-linked-list/
在这里插入图片描述
假如输入的为5,输出的应该为5,4,3,2,1
在这里插入图片描述
假如输入的为4,输出的应该为:4,3,2,1

在这里插入图片描述
使用递归方法实现:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        //空节点
        if(head==null){
            return null;
        }
        //只有一个头节点
        if(head.next==null){
            return head;
        }
        //递归反转链表
        ListNode newHead = reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return newHead;
    }
}

使用迭代方法实现:
在这里插入图片描述

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
	   public ListNode reverseList(ListNode head) {
	    
	    if(head==null || head.next==null){
	        return head;
	    }
	
	    //创建一个变量指向null
	    ListNode newHead = null;
	    while(head!=null){
	        ListNode temp = head.next;
	        //让head.next指向newHead
	        head.next = newHead;
	        //让newHead指向head
	        newHead = head;
	        head = temp;
	    }
	    return newHead;
	}
}
发布了665 篇原创文章 · 获赞 115 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/qq_42764468/article/details/104930278