鏈表反轉

來源:互聯網
上載者:User

即輸入鏈表1->2->3->4->5,反轉後為5->4->3->2->1。

#include "stdafx.h"<br />#include <stdio.h><br />#include <malloc.h></p><p>typedef struct _linka {<br />int data;<br />_linka* next;<br />}linka;</p><p>// Reverse link<br />void Reverse(linka*& head) {<br />if(head ==NULL)<br />{<br />return;<br />}</p><p>linka *pre, *cur, *ne;<br />pre=head;<br />cur=head->next;<br />while(cur)<br />{<br /> ne = cur->next;<br /> cur->next = pre;<br /> pre = cur;<br /> cur = ne;<br />}<br />head->next = NULL;<br />head = pre;<br />}</p><p>int n = 0;</p><p>// Create link<br />linka * CreateLink(void)<br />{<br />linka *head = NULL;<br />linka *pre = NULL;<br />linka *forward = NULL;</p><p>pre = forward = (linka *)malloc(sizeof(linka));<br />scanf("%d", &forward->data);</p><p>while(forward->data)<br />{<br />n++;<br />if( 1 == n )<br />{<br />// head node<br />head = pre;</p><p>}<br />else<br />{<br />pre->next = forward;<br />pre = forward;<br />forward = (linka *)malloc(sizeof(linka));<br />scanf("%d", &forward->data);<br />}<br />}</p><p>// Set last node to NULL<br />pre->next = NULL;</p><p>return head;<br />}</p><p>// Output link<br />void OutputLink(linka *head)<br />{<br />if( !head )<br />{<br />return;<br />}</p><p>// output first data<br />printf("%d ", head->data);</p><p>// output next data<br />while( head->next )<br />{<br />head = head->next;<br />printf("%d ", head->data);<br />}</p><p>printf("/n");<br />}</p><p>int _tmain(int argc, _TCHAR* argv[])<br />{</p><p>linka * head = CreateLink();</p><p>printf("Before reverse:/n");</p><p>OutputLink(head);</p><p>Reverse(head);</p><p>printf("After reverse:/n");</p><p>OutputLink(head);</p><p>getchar();</p><p>return 0;<br />}<br />

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.