剑指 Offer 10(链表篇2).反转链表
问题描述:
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
解题思路:
了解链表本身的性质,学会利用递归和栈的思想,具体详情见代码注释。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
利用迭代的方法实现链表反转
class Solution {
public ListNode reverseList(ListNode head) {
ListNode node = null;
while(head != null){
ListNode cur = head.next;
head.next = node;
node = head;
head = cur;
}
return node;
}
}
利用递归的方法实现链表反转
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode node = reverseList(head.next);
ListNode cur = head.next;
cur.next = head;
head.next = null;
return node;
}
}
利用栈实现链表反转
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null){
return head;
}
Stack<ListNode> stack = new Stack<>();
while(head != null){
stack.push(head);
head = head.next;
}
ListNode newHead = stack.pop();
ListNode newNode = newHead;
while(!stack.isEmpty()){
ListNode cur = stack.pop();
newNode.next = cur;
newNode = cur;
}
newNode.next = null;
return newHead;
}
}
|