Java 反转链接列表
我的问题是:给定一个函数来反转链表 我在C语言中的尝试是:Java 反转链接列表,java,linked-list,Java,Linked List,我的问题是:给定一个函数来反转链表 我在C语言中的尝试是: ListNode *reverse(ListNode *head) { if(head == NULL || head->next == NULL) return head; ListNode *temp = head->next; ListNode *retP = reverse(temp); temp->next = head; head->next
ListNode *reverse(ListNode *head)
{
if(head == NULL || head->next == NULL)
return head;
ListNode *temp = head->next;
ListNode *retP = reverse(temp);
temp->next = head;
head->next = NULL;
return retP;
}
但我认为这是不对的。我希望能够用Java来做这件事,对此我感到困惑。任何帮助都将不胜感激。请帮助我反复开始
public reverseListIteratively (Node head) {
if (head == NULL || head.next == NULL)
return; //empty or just one node in list
Node Second = head.next;
//store third node before we change
Node Third = Second.next;
//Second's next pointer
Second.next = head; //second now points to head
head.next = NULL; //change head pointer to NULL
//only two nodes, which we already reversed
if (Third == NULL)
return;
Node CurrentNode = Third;
Node PreviousNode = Second;
while (CurrentNode != NULL)
{
Node NextNode = CurrentNode.next;
CurrentNode.next = PreviousNode;
/* repeat the process, but have to reset
the PreviousNode and CurrentNode
*/
PreviousNode = CurrentNode;
CurrentNode = NextNode;
}
head = PreviousNode; //reset the head node
}
递归地
public void recursiveReverse(Node currentNode )
{
//check for empty list
if(currentNode == NULL)
return;
/* if we are at the TAIL node:
recursive base case:
*/
if(currentNode.next == NULL)
{
//set HEAD to current TAIL since we are reversing list
head = currentNode;
return; //since this is the base case
}
recursiveReverse(currentNode.next);
currentNode.next.next = currentNode;
currentNode.next = null; //set "old" next pointer to NULL
}
源代码,附带说明(使用google 3秒钟后)如果您想在Java中反转列表,请使用
Collections.reverse(List list)
如果您想知道它是如何实现的,或者想手工实现,请查看 请参阅以下链接:此代码是否在java中可能重复?如果不是的话,为什么要用JAVA标记呢?当然,你永远不需要写这篇文章,也许除了在采访中。最简单的解决方案是复制一些在必要时可以工作的东西,或者使用内置函数,因此实际上知道这个问题的答案,以及其他许多可以用另一种方法更好地解决的问题,并不值得知道IMHO。
public Node reverse(Node node){
Node p=null, c=node, n=node;
while(c!=null){
n=c.next;
c.next=p;
p=c;
c=n;
}
return p;
}