顿搜
飞过闲红千叶,夕岸在哪
类目归类
Reverse a singly linked list.
public ListNode reverseList(ListNode head)
{
if (head == null || head.next == null) {
return head;
}
ListNode pre = head;
ListNode node = head.next;
head.next = null;
ListNode front = node.next;
while (front != null) {
node.next = pre;
pre = node;
node = front;
front = front.next;
}
node.next = pre;
return node;
}public class LeetCode0206 {
static class ListNode {
int val;
ListNode next;
public ListNode(int x) { val = x; }
}
public ListNode reverseList(ListNode head)
{
if (head == null || head.next == null) {
return head;
}
ListNode pre = head;
ListNode node = head.next;
head.next = null;
ListNode front = node.next;
while (front != null) {
node.next = pre;
pre = node;
node = front;
front = front.next;
}
node.next = pre;
return node;
}
public static void main(String[] args)
{
ListNode listNode1 = new ListNode(1);
ListNode listNode2 = new ListNode(2);
listNode1.next = listNode2;
listNode2.next = null;
LeetCode0206 leetcode = new LeetCode0206();
ListNode head = leetcode.reverseList(listNode1);
System.out.println(head.val + "->" + head.next.val);
}
}