链表反转思路:
1.单链表中有效节点的个数
2.查找单链表中弟第k个节点
3.单链表的反转
实现代码如下:
public class TestLink { public static void main(String[] args) { //先创建节点 HeroNode hero1 = new HeroNode(1, "宋江", "及时雨"); HeroNode hero2 = new HeroNode(2, "卢俊义", "玉麒麟"); HeroNode hero3 = new HeroNode(3, "吴用", "智多星"); HeroNode hero4 = new HeroNode(4, "林冲", "豹子头"); //创建链表 SingleLinkedList list = new SingleLinkedList(); list.addByOrder(hero1); list.addByOrder(hero4); list.addByOrder(hero3); list.addByOrder(hero2); /*int aa = TestLink.count(list.getHead()); System.out.println(aa); HeroNode hero5 = TestLink.findHeroNode(list.getHead(),2); System.out.println(hero5.toString());*/ TestLink.reverse(list.getHead()); list.list(); } //1单链表中有效节点的个数 //--遍历得出个数 public static int count(HeroNode head){ if(head.next==null){ return 0; } int count = 0; while(true){ head = head.next; count++; if(head.next==null){ break; } } return count; } //2.查找单链表中弟第k个节点 //--先找到总长度 //--然后算出在第几个 遍历 public static HeroNode findHeroNode(HeroNode head,int k){ if(head.next==null){ return null; } int size = count(head); if(size<k||k<=0){ return null; } int index = 0; while(true){ head = head.next; if(index==(size-k)){ break; } index++; } return head; } //3.单链表的反转 //--创建一个新的头部 //--循环列表 逐步把遍历到的插入新的头部后面 //--把原来的头部 指向新的队列 public static void reverse(HeroNode head){ if(head.next==null){ System.out.println("链表为空"); return; } HeroNode rever = new HeroNode(0, "", ""); HeroNode next = null; HeroNode cru = head.next; while(cru!=null){ next = cru.next; cru.next = rever.next; rever.next=cru; cru=next; } head.next = rever.next; } }