LeetCode刷题实战206:反转链表
共 2854字,需浏览 6分钟
·
2021-03-14 14:06
Given the head of a singly linked list, reverse the list, and return the reversed list.
题意
示例
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
解题
public class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode cur1 = dummyHead;
if(cur1.next == null || cur1.next.next == null) {
return head;
}
ListNode cur2 = cur1.next;
ListNode cur3 = cur2.next;
while(cur3 != null) {
cur2.next = cur3.next;
ListNode temp = cur1.next;
cur1.next = cur3;
cur3.next = temp;
cur3 = cur2.next;
}
return dummyHead.next;
}
}