题目描述
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
题意理解
1、代码1:这道题有点类似两个值交换,节点的指向相反
设置两个变量,一个用来保存当前的值,一个用来保存链表下一个值
代码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) {
ListNode prev = null;
//如果链表是1->2->3->4->5,这时head为1
while(head != null){
//记录当前节点的下一个节点
ListNode next = head.next;
//将当前节点指向prev
head.next = prev;
//prev和head前进一位
prev = head;
head = next;
}
return prev;
}
}
代码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 cur = reverseList(head.next);
head.next.next = head;
head.next = null;
return cur;
}
}
参考:https://leetcode.com/problems/reverse-linked-list/discuss/58125/In-place-iterative-and-recursive-Java-solution