奇怪的uscis case status update# EB23 - 劳工卡
l*n
1 楼
现有两种方法,一种递归,一种直接存指针反转。哪种好?
Java版
static List Reverse(List L)
{
//firstly check if L is empty or only has one element then return
if(L==null || L.next==null)
return L;
//otherwise, we can use our recursive method
List remainingReverse = Reverse(L.next);
//next we have two step steps, firstly we need update the tail of
remaining reverse as our head L
L.next.next = L;//this (L.next) is the key to get te tail in constant
time!
//Very important, we need set L.next to NULL after that! Otherwise it's
causing cycles in list
L.next = null;
//finally we return the reverse List
return remainingReverse;
}
C++版
ListNode* ReverseList(ListNode* pHead)
{
ListNode* pReversedHead = NULL;
ListNode* pNode = pHead;
ListNode* pPrev = NULL;
while(pNode != NULL)
{
ListNode* pNext = pNode->m_pNext;
if(pNext == NULL)
pReversedHead = pNode;
pNode->m_pNext = pPrev;
pPrev = pNode;
pNode = pNext;
}
return pReversedHead;
}
Java版
static List Reverse(List L)
{
//firstly check if L is empty or only has one element then return
if(L==null || L.next==null)
return L;
//otherwise, we can use our recursive method
List remainingReverse = Reverse(L.next);
//next we have two step steps, firstly we need update the tail of
remaining reverse as our head L
L.next.next = L;//this (L.next) is the key to get te tail in constant
time!
//Very important, we need set L.next to NULL after that! Otherwise it's
causing cycles in list
L.next = null;
//finally we return the reverse List
return remainingReverse;
}
C++版
ListNode* ReverseList(ListNode* pHead)
{
ListNode* pReversedHead = NULL;
ListNode* pNode = pHead;
ListNode* pPrev = NULL;
while(pNode != NULL)
{
ListNode* pNext = pNode->m_pNext;
if(pNext == NULL)
pReversedHead = pNode;
pNode->m_pNext = pPrev;
pPrev = pNode;
pNode = pNext;
}
return pReversedHead;
}