简单的链表训练
链表
基本实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| function Node(e){ this.e = e; this.next = null; }
function find (item){ let currNode = this.head; while(currNode.e!=item){ currNode = currNode.next; } return currNode; }
function insert (newElement,item){ let newNode = new Node(newElement); let target = this.find(item); newNode.next= target.next; target.next = newNode; }
function display(){ let currNode = this.head; while(currNode){ console.log(currNode.e); currNode = currNode.next; } }
function LList() { this.head = new Node('head'); this.find = find; this.insert = insert; this.display = display; }
|
典型例题:
两两交换链表中的节点-24
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
示例:
1 2
| 给定 1->2->3->4, 你应该返回 2->1->4->3. 复制代码
|
来源:力扣(LeetCode)
链接:leetcode-cn.com/problems/sw…
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function switchwithnext(node){ if(!node) return null; let nextnode = node.next; if(!nextnode) return node; node.next = switchwithnext(nextnode.next); nextnode.next = node; return nextnode; }
function solution(head){ let res = switchwithnext(head); return res; }
|
难吗?还行,重点是next的理解,要画图.