3月打卡活动第2天LeetCode第206题:反转链表(简单)
- 题目:反转一个单链表。
- 解题思路1:想起了第25题,思路一样的。
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null) return head;
ListNode startNode = head,stopNode = head;
while(stopNode.next!=null){
stopNode = stopNode.next;
}
stopNode = reverse(startNode,stopNode);
return stopNode;
}
ListNode reverse(ListNode startNode, ListNode stopNode){
ListNode pre = null, cur = startNode, stop = stopNode.next;
while(cur!=stop){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}
- 解题思路2:题中要求用迭代或递归,我又试了试。从后往前依次取,我这叫迭代不。。。
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null) return head;
int count=0;
ListNode stopNode = head;
while(stopNode.next!=null){
stopNode = stopNode.next;
count++;
}
ListNode startNode = stopNode;
while(count>0){
stopNode.next=reverse(head,--count);
stopNode=stopNode.next;
}
return startNode;
}
ListNode reverse(ListNode startNode,int count){
ListNode pre = null,cur = startNode;
while(count>0){
cur = cur.next;
count--;
}
cur.next=pre;
return cur;
}
}
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/reverse-linked-list/solution/fan-zhuan-lian-biao-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。