Reverse a linked list.
Have you met this question in a real interview? Yes
Example
For linked list 1->2->3, the reversed linked list is 3->2->1
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The head of linked list.
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
// write your code here
ListNode prev = null;
while (head != null) {
ListNode temp = head.next;
head.next = prev;
prev = head;
head = temp;
}
return prev;
}
}
本文介绍了一种简单有效的方法来反转链表。通过迭代的方式,利用三个指针:当前节点、前一个节点及下一个节点,逐步将链表节点的指向反转,最终实现整个链表的反转。该方法适用于各种类型的链表。
178

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



