解法1.双指针
/**
* 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) {
ListNode pre=null,cur=head,t=null;
while(cur!=null){
t = cur.next;
cur.next = pre;
pre = cur;
cur = t;
}
return pre;
}
}
解法2.栈
/**
* 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) {
Stack<ListNode> stk=new Stack<>();
ListNode cur=head;
while(cur!=null){
stk.add(cur);
cur=cur.next;
}
ListNode pHead=new ListNode();
cur=pHead;
while(!stk.empty()){
ListNode bb=stk.pop();
cur.next=bb;
cur=cur.next;
}
cur.next=null;//最后一个元素next赋值为空
return pHead.next;
}
}