[英]Reversing a linked list
My problem is: Given a function to reverse a linked list. 我的问题是:给定一个反转链表的功能。
My attempt at it in C was: 我在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 = NULL;
return retP;
}
But I do not think this is right. 但我不认为这是对的。 I want to be able to do it in Java and I am stumped on this.
我希望能够用Java做到这一点,我对此感到难过。 Any help would be appreciated.
任何帮助,将不胜感激。 Please help me get started
请帮我开始吧
If you want to reverse a List in Java, use 如果要在Java中反转List,请使用
Collections.reverse(List list)
If you want to know how it is implemented or want to do it by hand, have a look at the JDK sources of java.util.Collections
. 如果您想知道它是如何实现的或想要手动完成,请查看
java.util.Collections
的JDK源代码 。
Iteratively 迭代
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
}
Recursively 递归
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
}
Source, with explanation (after using google for 3 seconds) http://www.programmerinterview.com/index.php/data-structures/reverse-a-linked-list/ 来源,有解释(使用谷歌3秒后) http://www.programmerinterview.com/index.php/data-structures/reverse-a-linked-list/
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.