题目:Reverse Linked List
Reverse
a singly linked list.
One:基本迭代
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null){return head;}
ListNode p1 = head;
ListNode p2 = head.next;
head.next = null;
while(p1!=null&&p2!=null){
ListNode temp = p2.next;
p2.next = p1;
p1 = p2;
p2 = temp;
}
return p1;
}
}Two:递归Recursive
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next == null)
return head;
ListNode second = head.next;
head.next = null;
ListNode rest = reverseList(second);
second.next = head;
return rest;
}
}
本文介绍了两种实现单链表逆序的方法:一种是通过迭代的方式进行逆序处理,另一种则是利用递归的方式完成逆序操作。对于每种方法都提供了详细的代码实现,并对关键步骤进行了说明。
434

被折叠的 条评论
为什么被折叠?



