Reverse Linked List(算法)
数据结构课上学的单向链表的知识都快忘完了……
看到题目的时候,大概的想法是,把head.next.next保存下来,然后next指针再指回去。具体实现中出现了种种问题T.T
所以还是没忍住,去百度了一下链表倒序的相关代码,发现比想象中更精炼,需要保存前后指针,这样思路会更加明晰。
题目
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
TAG:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode reverseList(ListNode head) { 11 if(head==null) 12 return null; 13 ListNode p=head,pNext=null,pFormer=null;//pFormer->p->pNext 14 while(p!=null){ 15 pNext = p.next; //暂存下一个节点,作为倒序后的前序节点 16 p.next = pFormer; //p指向倒序后的后序节点,若是head节点则指向null 17 pFormer = p;//当前节点作为下一个节点的前序节点 18 p = pNext;//节点指针后移 19 } 20 return pFormer;//最后节点指针后移到null时,退出while循环,此时pFormer指向链表最后一个元素(新链表第一个元素) 21 } 22 }
2.递归解法:(recursively,效率较低)
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 11 ListNode pFormer=null; 12 public ListNode reverseList(ListNode head) { 13 if(head==null) 14 return null; 15 ListNode pNext=null; 16 pNext = head.next; 17 head.next = pFormer; 18 pFormer = head; 19 reverseList(pNext); 20 return pFormer; 21 } 22 }
__________________________________________________________
shoobie do lang lang ^^