206,反轉連結串列
阿新 • • 發佈:2018-11-05
反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL 輸出: 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) {
if(head==null) return head;
ListNode dumy=new ListNode(0);
dumy.next=head;
ListNode cur=dumy.next;
while(cur.next!=null)
{
ListNode tmp=cur.next;
cur.next=tmp.next;
tmp.next=dumy.next;
dumy.next=tmp;
}
return dumy.next;
}
}