leetcode 206. Reverse Linked List
Reverse a singly linked list.Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
/**
* 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 temp = new ListNode(0);
while(head != null){
temp.val = head.val;
ListNode temp1 = new ListNode(0);
temp1.next = temp;
temp = temp1;
head = head.next;
}
return temp.next;
}
}
页:
[1]