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) {
Stack<ListNode> stock=new Stack<ListNode>();
if(head==null) return null;
if(head.next==null) return head;
while(head!=null){
stock.push(head);
head=head.next;
}
head=stock.pop();
ListNode cur=head;
while(stock.size()>0){
ListNode node=stock.pop();
node.next=null; //将之前存在指针取消掉
cur.next=node;
cur=node;
}
return head;
}
}
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) {
ListNode cur=head,pre=null;
while(cur!=null){
ListNode temp=cur.next; //暂存下一个节点,防止丢失
cur.next=pre; //指向前驱
pre=cur; //移动
cur=temp;
}
return pre;
}
}