方法一:采用迭代
/**
* 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 curr=head;
while(curr!=null){
ListNode temp=curr.next;
curr.next=pre;
pre=curr;
curr=temp;
}
return pre;
}
}
完整的运行实例
public class maintest {
public static void main(String[] args) {
//创建链表list1,链表有2个结点
ListNode list1 = new ListNode(1);
list1.next=new ListNode(2);
//遍历list1的链表
ListNode temp1=list1; //定义一个指针temp1指向list1头结点
while(temp1!=null){
System.out.println(temp1.val);
temp1=temp1.next;
}
//遍历反转后的链表list2
Solution s1=new Solution();
ListNode list2=s1.reverseList(list1); //返回list2的头结点
ListNode temp2=list2;
while(temp2!=null){
System.out.println(temp2.val);
temp2=temp2.next;
}
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
//注意java的函数都需要定义在一个类中
class Solution{
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
}
方法二:采用递归
思路解析
注意:这里ListNode p始终返回的是新链表的结点
帮助理解1
帮助理解2
/**
* 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; //这句话用于判断如果链表本身就是空链表或者到了链表的最后一个结点
ListNode p = reverseList(head.next);
head.next.next=head;
head.next=null;
return p;
}
}
参考链接
https://leetcode-cn.com/problems/reverse-linked-list/solution/fan-zhuan-lian-biao-by-leetcode/