單鏈表逆序(三種方式)

2021-07-11 22:46:59 字數 1658 閱讀 9248

三種方式實現單鏈表的逆序,分別是頭結點插入,對稱交換和利用堆疊來實現。三種方式分別是出於空間和時間的考慮來實現的,詳見注釋。

public

class

linkedlist

public

node(object data, node next)

public node getnext()

public

void

setnext(node next)

public object getdata()

public

void

setdata(object data)

}private node head;

public node first()

public node tail()

public node head()

public

linkedlist()

public

boolean

addstack(object data, node head)

return flag;

}public

boolean

addqueue(object data, node head)

return flag;

}public

void

print(node head)

system.out.println("list node data :" + temp.data);

}public

void

addqueue()

//直接頭結點插入

public linkedlist invertedlist(node head)

addstack(temp.data, newlist.head);

return newlist;

}public

intlength()

return i;

}//交換兩個對應的資料來實現,鍊錶逆序

public

void

invertedlistexchange(node head)

while (i != 0 && tempend.next.data != old)

tempend = tempend.next;

system.out.println(tempstart.data);

object tt = tempstart.data;

tempstart.data = tempend.data;

tempend.data = tt;

old = tempend.data;

tempstart = tempstart.next;}}

//利用棧的性質來實現

public linkedlist invertedlistbystack(node head)

stack.push(temp.data);

linkedlist newlist = new linkedlist();

node node = newlist.head;

while (!stack.isempty())

return newlist;

}}

單鏈表逆序三種方法

需要三個指標,前驅p1,當前p2,後繼p3 結束的條件是p2 null void reverse1 pnode head p1 p2 p2 p3 head next p1 head變成新頭節點返回 else return pnode reverse1 pnode head p1 p2 p2 p3 r...

單鏈表逆序的多種方式

template void list inverse first link prev 最後連上附加頭結點 link node reverselink link node head return prev 單鏈表反轉 逆序 status listreverse linklist l printf cu...

單鏈表逆序

include include typedef struct student student typedef struct list list,list list createlist void paixu list l 比較笨拙的一種方法 list reverse list l int main ...