トピック:リンクリストを入力し、リンクリストを逆にした後、新しいリンクリストのヘッダーを出力します。
入力:1→2→3→4→5
出力:5→4→3→2→1
問題解決のアイデア:
3つの変数pNode、pNext、およびpreを定義します。
1. pNextは、2番目のノードであるpNode.nextと同じです。
2. pNode.next(2番目のノード)はブリッジpreと同じです
3. PreはpNodeと等しく、2番目のノードが最初のノードを指すようにします。
4.pNodeはpNextと同じです。次の変換が行われるように、3つの変数を2番目のノードと等しくします。
最終的なコードは次のとおりです。
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function ReverseList(pHead)
{
pNext = pHead;
pNode = pHead;
var pre = null
while(pNode){
pNext = pNode.next;
pNode.next = pre;
pre = pNode;
pNode = pNext;
}
return pre;
}
解決策2:
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function ReverseList(pHead)
{
let newHead = null;
while(pHead){
let tmpNode= newHead;
newHead = new ListNode(pHead.val);
newHead.next = tmpNode;
pHead = pHead.next;
}
return newHead;
}