翻转链表
题目
翻转一个链表
样例
给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
挑战
在原地一次翻转完成
题解
遍历链表,将每一个节点的下一个节点,指向前面的节点,即把当前节点作为新的反转链表头结点。
/**
* 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) {
if (head == null)
{
return head;
}
ListNode p = head;
ListNode next = null;
ListNode pre = null;
while(p != null)
{
next = p.next;
p.next = pre;
pre = p;
p = next;
}
return pre;
}
}
Last Update 2016.8.26