Reverse a singly linked list.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if (head==null || head.next==null) {
return head;
}
ListNode pre = null;
ListNode cur = head;
ListNode nex = null;
while (head != null) {
nex = head.next;
head.next = pre;
pre = head;
head = nex;
}
return pre;
}
}
本文介绍了一种反转单链表的方法,通过迭代的方式实现链表节点的反转操作。具体步骤包括初始化三个指针变量:前驱节点pre、当前节点cur及下一个节点nex;当头节点不为空时,依次更新这三个指针的指向,最终返回新的头节点。
553

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



