地址
https://leetcode.cn/problems/reverse-linked-list/
解题思路
- 反转链表
1,需要遍历head的链表,取出node。
2,新建一个链表,每次赋值为倒序,即将新取出的node设置为新链表的head。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null){
return null;
}
ListNode last = new ListNode(head.val);
while (head.next !=null){
last = new ListNode(head.next.val,last);
head = head.next;
}
return last;
}
}