/*function ListNode(x){ this.val = x; this.next = null; }*/ function ReverseList(pHead) { // write code here var head = {} head.next = pHead if(pHead == null || pHead.next == null) {return pHead} var current = null var next = null current = head.next.next head.next.next = null while(current!=null) { next = current.next current.next = head.next head.next = current current = next } return head.next } module.exports = { ReverseList : ReverseList };
function node(id,name) { this.id = id; this.name = name; this.next = null; } function linkList(id,name) { this.header = new node(id,name) } linkList.prototype = { addNode: function (node) { var current = this.header while(current.next!=null){ if(current.next.id>node.id){ break; } current = current.next } node.next = current.next; current.next = node; }, getLinkList: function () { var current = this.header if(current.next == null){ console.log('链表为空') return } var txt = '' while(current.next!=null){ txt += current.next.name + ' ' if(current.next.next == null){ break; } current = current.next } console.log(txt) }, clear: function () { this.header = null }, reverse: function () { var head = this.header if(head == null || head.next == null){ console.log('链表为空') } var current = null //当前节点 var next = null //后继节点 current = head.next.next // 将首节点设为尾结点 head.next.next = null while(current!=null){ next = current.next current.next = head.next head.next = current current = next } } } var lists = new linkList() for(var i=0;i<8;i++){ lists.addNode(new node(i,i)) } lists.getLinkList() // 0 1 2 3 4 5 6 7 lists.reverse() lists.getLinkList() // 7 6 5 4 3 2 1 0