题目:
Reverse a singly linked list.
题意:
倒转单链表.
算法分析:
方法一:
将单链表转化为数组,利用数组倒序重建新的单链表。
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution
{
public static ListNode reverseList(ListNode head)
{
ArrayList<Integer> list =new ArrayList<Integer>();
int k=0;
int i;
if(head==null) return head;
while(head!=null)
{
list.add(head.val);
head=head.next;
k++;
}
ListNode res = new ListNode(list.get(k-1));;
ListNode newhead = res;
//newhead.next=res;
for(i=k-1;i>=1;i--)
{
res.next=new ListNode(list.get(i-1));
res=res.next;
}
return newhead;
}
}
方法二:
单链表指针反转
代码:
public class Solution
{
public ListNode reverseList(ListNode head)
{
ListNode dunmy = head; //维护初始链表头,用于判断循环结束
if(head == null || head.next == null)
return head;
ListNode pre = null;
ListNode temp = null;
while(dunmy.next != null)
{
pre = head; //记录当前节点
head = dunmy.next;
temp = head.next; //保存next
head.next = pre;
dunmy.next = temp;
}
return head;
}
}