
问题
Reverse a singly linked list.
Example:
Input:1->2->3->4->5->NULL
Output:5->4->3->2->1->NULL
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre=null;
ListNode next=null;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
//此时注意:1、关于指针的是head.next指向pre
2、关于赋值的是把后面的值赋给前面,比如pre=head,是把head的值赋给pre
return pre;
}
}
反转双向链表
/**
* Definition for singly-linked list.
* public class DoubleNode {
* int val;
* DoubleNode last;
* DoubleNode next;
* DoubleNode(int x) { val = x; }
* }
*/
class Solution {
public DoubleNode reverseList(DoubleNode head) {
DoubleNode pre=null;
DoubleNode next=null;
while(head!=null){
next=head.next;
head.next=pre;
head.last=next;
pre=head;
head=next;
}
return pre;
}
}
近期评论