关于单链表的一些代码题
作者:互联网
public class LinkedList { public LinkedNode head; public void removeAllVal(int val) { if (this.head == null) {//判断链表是否为空 return ; } LinkedNode prev = this.head; LinkedNode cur = this.head.next; while(cur != null) {//判断遍历完链表 if (cur.val == val) { prev.next = cur.next; }else{ prev = cur; } cur = cur.next; } if (this.head.val == val ) {//头节点单独判断,容易做。 this.head = this.head.next; } } }
public class LinkedList { public LinkedNode head; public LinkedNode reverseList( ) { LinkedNode curNext = null;//记录cur.next的位置 LinkedNode prev = null;//记录反转时,cur.next的指向 LinkedNode cur = this.head; while (cur != null) {//遍历链表 curNext = cur.next; cur.next = prev; prev = cur; cur = curNext; } return prev;//新的头节点 } }
3、给定一个带有头结点 head 的非空单链表,返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点
public class LinkedList { public LinkedNode head; public LinkedNode middleNode() { if (this.head == null) { return null; } LinkedNode fast = this.head; LinkedNode slow = this.head; while (fast != null && fast.next != null ) {//奇数长度和偶数长度的单链表情况都考虑进去 fast = fast.next.next;//fast一次走两步 slow = slow.next;//slow一次走一步 } return slow; } }
public class LinkedList { public LinkedNode head; public LinkedNode findKthToTail(int k) { if (k <= 0 || this.head == null ) {//判断k的合法性以及单链表是否为空 return null; } LinkedNode fast = this.head; LinkedNode slow = this.head; while (fast.next != null) { while (k - 1 != 0) { fast = fast.next;//先让fast走k-1步 if (fast == null) {//判断了k大于链表长度时的情况 System.out.println("没有这个节点!"); return null; } k--; } fast = fast.next;//两个指针同时走 slow = slow.next;// } return slow; } }
5、将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的
public class Test { public LinkedNode mergeTwoList(LinkedNode head1,LinkedNode head2) { LinkedNode newHead = new LinkedNode(-1);//虚拟一个傀儡节点 LinkedNode tmp = newHead; while (head1 != null && head2 != null) { if (head1.val < head2.val) {//排序 tmp.next = head1; head1 = head1.next; }else { tmp.next = head2; head2 = head2.next; } tmp = tmp.next; } if (head1 != null) {//其中一个遍历完成后,直接让tmp.next指向另一个单链表 tmp.next = head1; } if (head2 != null){ tmp.next = head2; } return newHead.next;//新的头节点 } }
标签:head,单链,cur,代码,next,关于,LinkedNode,null,public 来源: https://blog.csdn.net/yszhaonan/article/details/120937546