leetcode:#206 反转链表
采用Java实现。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution { //头插法
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
ListNode reverseHead = head;
ListNode currentNode = head.next;
reverseHead.next = null;
while(currentNode != null) {
ListNode nextNode = currentNode.next;
currentNode.next = reverseHead;
reverseHead = currentNode;
currentNode = nextNode;
}
return reverseHead;
}
}