?LeetCode刷題實(shí)戰(zhàn)206:反轉(zhuǎn)鏈表
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
進(jìn)階:
你可以迭代或遞歸地反轉(zhuǎn)鏈表。你能否用兩種方法解決這道題?
解題
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;
}
}
LeetCode1-200題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)201:數(shù)字范圍按位與
LeetCode刷題實(shí)戰(zhàn)202:快樂(lè)數(shù)
LeetCode刷題實(shí)戰(zhàn)203:移除鏈表元素
LeetCode刷題實(shí)戰(zhàn)204:計(jì)數(shù)質(zhì)數(shù)
LeetCode刷題實(shí)戰(zhàn)205:同構(gòu)字符串
