您的位置:首页 > 编程语言 > Java开发

Leetcode Reverse Linked List 反转单链表

2015-05-06 11:25 274 查看

题目:

Reverse a singly linked list.

分析:

1. 反转后头结点的next为null。

2. 需要同时记录三个节点,分别是当前节点,它的前节点和next节点。

Java代码实现:

/**
* 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 node = head;
ListNode pre = head.next;
node.next = null;

while(pre!=null)
{
ListNode temp = pre.next;
pre.next = node;
node = pre;
pre = temp;
}

return node;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息