public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode reverseList(ListNode head) {
***这里为具体实现,返回链表的头结点***
}
- 采用迭代的方式实现
/**
* 迭代实现,使用三个变量,存放前继节点、当前节点、后节点,每次修改当前节点的指向为前继节点
*/
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode next = null;
while (cur!=null){
next = cur.next;
cur.next = pre;
if(next==null){
return cur;
}
pre = cur;
cur = next;
}
return cur;
}