题目链接:https://leetcode.com/problems/reverse-linked-list/
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
思路:就地反转
具体就是
1-2-3-4-5
第一次1 2-3-4-5
第二次2-1 3-4-5
第三次3-2-1 4-5
第四次4-3-2-1 5
第五次5-4-3-2-1
AC 0ms:
/**
* 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;
ListNode cur=head;
while(cur!=null){
ListNode temp=cur.next;
cur.next=prev;
prev=cur;
cur=temp;
}
return prev;
}
}