1.链表转数组

  1. function listToArray(list){
  2. const res = [];
  3. while(list !== null){
  4. res.push(list.val)
  5. list = list.next
  6. }
  7. return res;
  8. }

2.数组转链表

  1. function arrayToList(arr){
  2. if(!arr.length){
  3. return null
  4. }
  5. let head = {val:arr[0],next:null}
  6. let pnode = head
  7. let node = null;
  8. for(let i = 1; i < arr.length; i++){
  9. node = {val:arr[i],next:null}
  10. pnode.next = node;
  11. pnode = pnode.next
  12. }
  13. return head;
  14. }