leetcode206 Reverse Linked List

来源:互联网 发布:linux 端口映射工具 编辑:程序博客网 时间:2024/04/29 01:57

Reverse Linked List

Reverse a singly linked list.

public class Solution {


public ListNode reverseList(ListNode head) {
if(head==null || head.next==null)
return head;
if(head.next.next==null){
head.next.next = head;
ListNode w = head.next;
head.next = null;
return w;
}
ListNode p = head;
ListNode q = p.next;
ListNode r = q.next;
p.next = null;
while(r.next!=null){
q.next = p;
p = q;
q = r;
r = r.next;
}

q.next = p;
r.next = q;
return r;
}
public static void show(ListNode head) {
while (head != null) {
System.out.println(head.val);
head = head.next;
}
}
public static void main(String[] args) {
int a[] = { 1,2,3,4,5};
ListNode head = new ListNode(a[0]);
ListNode p = head;
for (int i = 1; i < a.length; i++) {
ListNode q = new ListNode(a[i]);
p.next = q;
p = q;
}
head = new Solution().reverseList(head);
show(head);
}


}


class ListNode {
int val;
ListNode next;


ListNode(int x) {
val = x;
}
}

0 0
原创粉丝点击