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;
}
}