3 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
一個(gè)回復(fù)中的代碼說(shuō)明了這一點(diǎn),但是您可能會(huì)發(fā)現(xiàn)通過(guò)詢(xún)問(wèn)和回答微小的問(wèn)題(這是The Little Lisper中的方法)從下往上開(kāi)始更容易:
null的反轉(zhuǎn)是什么(空列表)?空值。
單元素列表的反轉(zhuǎn)是什么?元素。
n元素列表的反轉(zhuǎn)是什么?與列表其余部分相反的是第一個(gè)元素。
public ListNode Reverse(ListNode list){ if (list == null) return null; // first question if (list.next == null) return list; // second question // third question - in Lisp this is easy, but we don't have cons // so we grab the second element (which will be the last after we reverse it) ListNode secondElem = list.next; // bug fix - need to unlink list from the rest or you will get a cycle list.next = null; // then we reverse everything from the second element on ListNode reverseRest = Reverse(secondElem); // then we join the two lists secondElem.next = list; return reverseRest;}

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
我在接受采訪時(shí)被問(wèn)到這個(gè)問(wèn)題,并且因?yàn)槲矣悬c(diǎn)緊張而感到煩惱。
這應(yīng)該反轉(zhuǎn)一個(gè)單鏈表,用反向調(diào)用(head,NULL); 所以如果這是你的清單:
1-> 2-> 3-> 4-> 5->空它會(huì)變成:5-> 4-> 3-> 2-> 1->空
//Takes as parameters a node in a linked list, and p, the previous node in that list //returns the head of the new list Node reverse(Node n,Node p){ if(n==null) return null; if(n.next==null){ //if this is the end of the list, then this is the new head n.next=p; return n; } Node r=reverse(n.next,n); //call reverse for the next node, //using yourself as the previous node n.next=p; //Set your next node to be the previous node return r; //Return the head of the new list }
編輯:我已經(jīng)完成了6次編輯,顯示它對(duì)我來(lái)說(shuō)仍然有點(diǎn)棘手lol

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超9個(gè)贊
我得到了一半(直到null,并且由plinth建議的一個(gè)節(jié)點(diǎn)),但在進(jìn)行遞歸調(diào)用后失去了軌道。然而,在閱讀了基座的帖子后,我想出了以下內(nèi)容:
Node reverse(Node head) { // if head is null or only one node, it's reverse of itself. if ( (head==null) || (head.next == null) ) return head; // reverse the sub-list leaving the head node. Node reverse = reverse(head.next); // head.next still points to the last element of reversed sub-list. // so move the head to end. head.next.next = head; // point last node to nil, (get rid of cycles) head.next = null; return reverse;}
添加回答
舉報(bào)