题目描述:Reverse a singly linked list.
解题思路:从头指针开始依次改变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) {
ListNode p;
ListNode q;
if(head==null) return head;
p=head.next;
if(p==null) return head;
q=head;
while(p.next!=null){
ListNode temp;
temp=p.next;
p.next=q;
q=p;
p=temp;
}
p.next=q;
head.next=null;
head=p;
return head;
}
}
原题地址:
https://leetcode.com/problems/reverse-linked-list/