1.直接操作链表实现链表反转
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode pre = null;
ListNode tmp = null;
while(cur != null){
tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}
2.建立虚结点,实现链表反转
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = new ListNode(0);
ListNode cur = head;
while(cur != null){
ListNode tmp = cur.next;
cur.next = pre.next;
pre.next = cur;
cur = tmp;
}
return pre.next;
}
}
3.递归
class Solution {
public ListNode reverseList(ListNode head) {
//递归停止条件
if(head == null || head.next == null){
return head;
}
//递归
ListNode ret = reverseList(head.next);
//反转
head.next.next = head;
//当前结点的next指向null
head.next = null;
return ret;
}
}
4.另一种双指针
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head;
if(head == null)
return null;
while(head.next != null){
//tmp指向下次循环要处理的结点
ListNode tmp = head.next.next;
//实现反转
head.next.next = cur;
//cur移动到已经反转好的结点上
cur = head.next;
//指向下轮要处理的结点
head.next = t;
}
return cur;
}
}