国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

輸入一個鏈表,反轉鏈表后,輸出鏈表的所有元素。使得只掃描一次鏈表。

2019-11-08 01:44:32
字體:
來源:轉載
供稿:網友

輸入一個鏈表,反轉鏈表后,輸出鏈表的所有元素。使得只掃描一次鏈表。

思路:兩個指針p,q。p先掃K個,然后p,q同時向后,p到表尾的時候,q所指向的就是倒數k個節點。注意代碼的魯棒性(健壯性)排除異常輸入。

package com.mytest.mymain;class ListNode {	int val;	ListNode next = null;	ListNode(int val) {		this.val = val;	}}public class FindKthtotail {	public static void main(String[] args) {		FindKthtotail findKthtotail=new FindKthtotail();		ListNode One =new ListNode(2);		ListNode Two =new ListNode(3);		ListNode Third =new ListNode(4);		ListNode Four =new ListNode(5);		ListNode Five =new ListNode(6);		One.next=Two;		Two.next= Third;		Third.next=Four;		Four.next=Five;		ListNode head=new ListNode(1);		head.next=One;		ListNode result=findKthtotail.FindKthToTail(head,3);		System.out.PRintln(result.val);			}	public ListNode FindKthToTail(ListNode head, int k) {		if (head == null || k <= 0)			return null;		ListNode pListNode = head, qListNode = head;		for (int i = 1; i < k; ++i) {			if (pListNode.next != null) {				pListNode = pListNode.next;			} else {				return null;			}		}		while (pListNode.next != null) {			qListNode = qListNode.next;			pListNode = pListNode.next;		}		return qListNode;	}}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 莆田市| 曲周县| 延川县| 玉龙| 天等县| 正定县| 烟台市| 临西县| 四会市| 墨竹工卡县| 大埔区| 涡阳县| 盐城市| 康保县| 宝鸡市| 泰兴市| 云林县| 安龙县| 常山县| 察隅县| 高淳县| 邛崃市| 河津市| 湘阴县| 保亭| 定远县| 铅山县| 五指山市| 阿尔山市| 桓台县| 乌兰察布市| 临潭县| 庆云县| 玛多县| 涿州市| 荔浦县| 固阳县| 孟村| 漠河县| 汶川县| 衡阳市|