Reverse Linked List
Reverse a singly linked list.
反转一个单向链表,采用头插法,设定两个指针pre和tem,tem记录head的下一个元素,从head开始依次指向它前面的元素,同时pre不断后移。代码如下:
/**
* 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) {
ListNode pre = null;
ListNode tem = null;
while(head != null) {
tem = head.next;
head.next = pre;
pre = head;
head = tem;
}
return pre;
}
}