求鏈表倒數第幾個節點,倒數幾個節點

來源:互聯網
上載者:User

求鏈表倒數第幾個節點,倒數幾個節點

使用兩個指標,和判斷一個鏈表是否形成環類似

代碼:

#include <iostream>#include <list>using namespace std;typedef struct node {int data;struct node  *next ;}Node,*pNode;void creatNode( pNode &pHead ){bool isFirst=true;pNode p,q;int temp;scanf("%d",&temp);while(temp){p=(pNode)malloc(sizeof(Node));p->data = temp;p->next = NULL;if(isFirst){q=pHead=p;isFirst = false;}else{q->next = p;q = p;}scanf("%d",&temp);}}void print(pNode p){while(p){cout<<p->data << " ";p = p->next;}}pNode printLast(pNode pHead,unsigned int m){if(NULL == pHead || m==0)return NULL ;pNode pAhead = pHead;pNode pBehind = pHead;for(int i=1;i<=m;i++){if(pAhead->next != NULL)pAhead = pAhead->next;elsereturn NULL;}while(pAhead){pAhead = pAhead->next;pBehind = pBehind->next;}return pBehind;}int main(){   pNode pHead=NULL;creatNode(pHead);print(pHead);    cout<<endl<< printLast(pHead,2)->data;    return 0;}

運行結果:



單鏈表倒數第k個結點

Node* create_Link(int num)
{
Node* head,*p,*q;
p=new Node();
p->data=1;
head=p;
for (int i=2;i<=num;i++)
{
q=new Node();
q->data=i;
p->next=q;
p=q;
}
p=NULL;//最後一個節點指向空
return head;
}

Node* FindK(Node* head,int k)
{
Node* pslow,*pfast;
pslow=pfast=head;
int i=0;
while(i<k)
{
pfast=pfast->next;
i++;
}
while(pfast)
{
pfast=pfast->next;
pslow=pslow->next;
}
return pslow;
}

int _tmain(int argc, _TCHAR* argv[])
{
Node* head = create_Link(10);
Node* kNode=FindK(head,2);
cout<<kNode->data<<endl;

system("pause");
return 0;
}
 
單鏈表中倒數第k個元素 要:不可以利用鏈表中元素的個數 完整程式

既然不能用鏈表中的元素個數,那就得另想辦法了。
我給你思想吧。程式你自己寫了。
演算法思想:
1、單鏈表如果知道頭結點的指標,那麼可以順著結點的指標域一直找下去來遍曆元素。
2、那麼我們可以這樣,從第一個結點開始取值,然後判斷這個結點到單鏈表結束是不是倒數第k個,如果不是,繼續往下取第二個結點值,然後判斷這個結點到單鏈表結束是不是倒數第k個,後續依次。(其中要求判斷的是個迴圈)

還有一種演算法,最笨的 就是鏈錶轉換成順序表,不過這個順序表的空間可是個問題哦。

程式我不想代勞了。你自己練習吧。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.