Reverse a singly linked list.
solution:
1. Iteration:
two pointers go through linked list, reverse two neigbour list node.
2. Recursion
public ListNode reverseList(ListNode head) {
ListNode p1 = head;
if(head == null || head.next == null) return head;
ListNode p2 = head.next;
while(p2!=null){
ListNode p3 = p2.next;
p2.next = p1;
p1 = p2;
p2 = p3;
}
head.next = null;
return p1;
}public ListNode reverseList(ListNode head) {
if(head == null) return null;
if(head.next == null) return head;
ListNode secondElem = head.next;
head.next = null;
//reverse everything from the second element on
ListNode reverseRest = reverseList(secondElem);
//join the two lists
secondElem.next = head;
return reverseRest;
}

本文详细介绍了反转链表的两种方法:迭代法和递归法。通过两个函数实现,阐述了如何在链表中反转节点,并提供了解决问题的思路和代码示例。
1万+

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



